Part 2: Language Guide (The Basics, Basic Operators)

本文介绍了Swift编程语言的基础知识,包括常量和变量命名、多行注释、语句分号、数字类型的赋值和指数表示法、元组、可选类型、条件判断和异常处理等核心概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Part 2: Language Guide

1.1.3 Naming Constants and Variables


Constant and variable names can contain almost any character, including Unicode characters:


常量名、变量名的名字可以是Unicode字符


1.2 Comments

Unlike multiline comments in C, multiline comments in Swift can be nested inside other multiline comments. You write nested comments by starting a multiline comment block and then starting a second multiline comment within the first block. The second block is then closed, followed by the first block:


  • /* this is the start of the first multiline comment
  • /* this is the second, nested multiline comment */
  • this is the end of the first multiline comment */

Nested multiline comments enable you to comment out large blocks of code quickly and easily, even if the code already contains multiline comments.


多行的注释是可以嵌套的,事实上他们也是需要一对一的



1.3 Semicolons

Unlike many other languages, Swift does not require you to write a semicolon (;) after each statement in your code, although you can do so if you wish. Semicolons are required, however, if you want to write multiple separate statements on a single line:




swift语句是不用分号结尾的,除非你想把多个语句写在一行上



1.7Numeric Literals

Integer literals can be written as:

  • A decimal number, with no prefix 
  • A binary number, with a 0b prefix 
  • An octal number, with a 0o prefix 
  • A hexadecimal number, with a 0x prefix 

All of these integer literals have a decimal value of 17:


  • let decimalInteger = 17
  • let binaryInteger = 0b10001       // 17 in binary notation
  • let octalInteger = 0o21           // 17 in octal notation
  • let hexadecimalInteger = 0x11     // 17 in hexadecimal notation

不同进制的赋值


For decimal numbers with an exponent of exp, the base number is multiplied by 10exp:

  • 1.25e2 means 1.25 × 102, or 125.0
  • 1.25e-2 means 1.25 × 10-2, or 0.0125

十进制指数表示法


For hexadecimal numbers with an exponent of exp, the base number is multiplied by 2exp:

  • 0xFp2 means 15 × 22, or 60.0
  • 0xFp-2 means 15 × 2-2, or 3.75
  • 十六进制指数表示法


All of these floating-point literals have a decimal value of 12.1875:


  • let decimalDouble = 12.1875
  • let exponentDouble = 1.21875e1
  • let hexadecimalDouble = 0xC.3p0

Numeric literals can contain extra formatting to make them easier to read. Both integers and floats can be padded with extra zeroes and can contain underscores to help with readability. Neither type of formatting affects the underlying value of the literal:


  • let paddedDouble = 000123.456
  • let oneMillion = 1_000_000
  • let justOverOneMillion = 1_000_000.000_000_1

可以用下划线分隔,以便阅读


1.11Tuples

let http404Error = (404, "Not Found")

// http404Error is of type (Int, String), and equals (404, "Not Found")

let (statusCode, statusMessage) = http404Error

println("The status code is \(statusCode)")

// prints "The status code is 404"

println("The status message is \(statusMessage)")

// prints "The status message is Not Found"

let (justTheStatusCode, _) = http404Error

println("The status code is \(justTheStatusCode)")

// prints "The status code is 404"

println("The status code is \(http404Error.0)")

// prints "The status code is 404"

println("The status message is \(http404Error.1)")

// prints "The status message is Not Found"

let http200Status = (statusCode: 200, description: "OK")

println("The status code is \(http200Status.statusCode)")

// prints "The status code is 200"

println("The status message is \(http200Status.description)")

// prints "The status message is OK"


不知道人家怎么翻译这个词的,一个有多个部分组成的数据,可以一次把多个部分值取出来,也可以只取其中的某几个部分,可以用索引值取值,也可以用元素名称取值


1.12Optionals

You use optionals in situations where a value may be absent. An optional says:

  • There is a value, and it equals x 

or

  • There isn’t a value at all



var a: String?   //nil

var b = a?.toInt()  //nil

var c = a!.toInt() //Execution was interrupted,reason:EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0)


var a1: String? = "1" //{Some "1"}

var b1 = a1?.toInt()  //{Some 1}

var c1 = a1!.toInt()  //{Some 1}


因为不确定字符串能否转成整形,所以toInt()返回值是Int?类型


1.12.1nil


NOTE

Swift’s nil is not the same as nil in Objective-C. In Objective-C, nil is a pointer to a nonexistent object. In Swift, nil is not a pointer—it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types.


1.12.3Optional Binding


let possibleNumber = "123"

let convertedNumber = possibleNumber.toInt()//{Some 123}


if let actualNumber = possibleNumber.toInt() {

    println("\'\(possibleNumber)\' has an integer value of \(actualNumber)")

} else {

    println("\'\(possibleNumber)\' could not be converted to an integer")

}

// prints "'123' has an integer value of 123"

This code can be read as:

“If the optional Int returned by possibleNumber.toInt contains a value, set a new constant called actualNumber to the value contained in the optional.”

If the conversion is successful, the actualNumber constant becomes available for use within the first branch of the if statement. It has already been initialized with the value contained within the optional, and so there is no need to use the ! suffix to access its value. In this example, actualNumber is simply used to print the result of the conversion.


1.12.4Implicitly Unwrapped Optionals


var a: String  //初始化结果 String""

var a1: String//初始化结果  (String!)nil


a = a+"1"  //编译时提示Variable 'a' used before being initialized

a1 = a1+"1"  //运行时 fatal error: unexpectedly found nil while unwrapping an Optional value

通过调试发现


if a != nil {//ok

    

}


if a1 != nil {//ok

    

}


if let c = a {//Bound value in a conditional binding must be of Optional type

    

}


if let c = a1{//ok

    

}



1.13.2When to Use Assertions

Use an assertion whenever a condition has the potential to be false, but must definitely be true in order for your code to continue execution. Suitable scenarios for an assertion check include:

  • 1)An integer subscript index is passed to a custom subscript implementation, but the subscript index value could be too low or too high. 
  • 2)A value is passed to a function, but an invalid value means that the function cannot fulfill its task. 
  • 3)An optional value is currently nil, but a non-nil value is essential for subsequent code to execute successfully.


2.Basic Operators


2.3.1Remainder Operator


The remainder operator (a % b) works out how many multiples of b will fit inside a and returns the value that is left over (known as the remainder).


To determine the answer for a % b, the % operator calculates the following equation and returns remainder as its output:

a = (b × some multiplier) + remainder


9 % 4    // equals 1  9 = (4 × 2) + 1

-9 % 4   // equals -1  -9 = (4 × -2) + -1


The sign of b is ignored for negative values of b. This means that a % b and a % -b always give the same answer.



2.3.2Floating-Point Remainder Calculations


8 % 2.5   // equals 0.5



2.7Nil Coalescing Operator


The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

The nil coalescing operator is shorthand for the code below:


  • a != nil ? a! : b


var a:String? = "aaaa"  //{Some "aaaa"}

let b = "bbb"

let c = a ?? b          //"aaaa"

a = nil

let d = a ?? b          //"bbbb"


2.8Range Operators


2.8.1Closed Range Operator


for index in 1...5 {

    println("\(index) times 5 is \(index * 5)")

}

// 1 times 5 is 5

// 2 times 5 is 10

// 3 times 5 is 15

// 4 times 5 is 20

// 5 times 5 is 25


2.8.2Half-Open Range Operator


for index in 1..<5 {

    println("\(index) times 5 is \(index * 5)")

}

// 1 times 5 is 5

// 2 times 5 is 10

// 3 times 5 is 15

// 4 times 5 is 20



 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值