Swift 语言之基础学习笔记

常量和变量

用let来声明常量,用var来声明变量:

1
2
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0

类型标注:

1
2
var welcomeMessage: String = "Hello"
var red, green, blue: Double

输出常量和变量:

1
2
var friendlyWelcome = "Hello!"
println("The current value of friendlyWelcome is \(friendlyWelcome)")

注释

单行注释:

1
// this is a comment

多行注释(可以嵌套):

1
2
3
/* 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 */

分号

同一行内写多条独立语句:

1
2
let cat = "🐱"; println(cat)
// prints "🐱"

整数

整数范围:

1
2
let minValue = UInt8.min  // minValue is equal to 0, and is of type UInt8
let maxValue = UInt8.max // maxValue is equal to 255, and is of type UInt8

浮点数

类型安全和类型推断

整数推断

1
2
let meaningOfLife = 42
// meaningOfLife is inferred to be of type Int

浮点数推断:

1
2
let anotherPi = 3 + 0.14159
// anotherPi is also inferred to be of type Double

数值字面量

整数字面量(十进制数没有前缀,二进制数前缀是0b,八进制数前缀是0o,十六进制数前缀是0x):

1
2
3
4
let decimalInteger = 17
let binaryInteger = 0b10001 // 17 in binary notation
let octalInteger = 0o21 // 17 in octal notation
let hexadecimalInteger = 0x11 // 17 in hexadecimal notation

浮点字面量(十进制数没有前缀,指数通过e或E指定,十六进制通过p或P指定):

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

数值字面量增强可读性写法:

1
2
3
let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1

数值类型转换

整数转换:

1
2
3
let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one)

整数与浮点数转换:

1
2
3
4
let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine
// pi equals 3.14159, and is inferred to be of type Double

类型别名

类型别名就是给现有类型定义另外一个名字:

1
2
3
typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.min
// maxAmplitudeFound is now 0

布尔值

1
2
let orangesAreOrange = true
let turnipsAreDelicious = false

元组

元组就是把多个值组合成一个复合值:

1
2
3
4
5
6
7
8
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

如果只需要一部分元组值,分解的时候可以把要忽略的部分用下划线(_)标记:

1
2
3
4
let (justTheStatusCode, _) = http404Error

println("The status code is \(justTheStatusCode)")
// prints "The status code is 404

还可以通过下标来访问元组中的单个元素,下标从零开始:

1
2
3
4
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

可以在定义元组的时候给单个元素命名:

1
2
3
4
5
6
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

可选

可以给可选变量赋值为nil来表示它没有值:

1
2
3
4
var serverResponseCode: Int? = 404
// serverResponseCode contains an actual Int value of 404
serverResponseCode = nil
// serverResponseCode now contains no value

if语句强制解析:

1
2
3
4
5
6
7
8
let possibleNumber = "123"
let convertedNumber = possibleNumber.toInt()
// convertedNumber is inferred to be of type "Int?", or "optional Int

if convertedNumber != nil {
println("convertedNumber has an integer value of \(convertedNumber!).")
}
// prints "convertedNumber has an integer value of 123.

可选绑定:

1
2
3
4
5
6
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

隐式解析可选类型:

1
2
3
4
5
6
7
let possibleString: String? = "An optional string."
println(possibleString!) // requires an exclamation mark to access its value
// prints "An optional string."

let assumedString: String! = "An implicitly unwrapped optional string."
println(assumedString) // no exclamation mark is needed to access its value
// prints "An implicitly unwrapped optional string.

断言

使用断言调试:

1
2
3
let age = -3
assert(age >= 0, "A person's age cannot be less than zero")
// this causes the assertion to trigger, because age is not >= 0