Swift 编程语言教程

Swift 编程语言教程

1. 可选类型(Optionals)

Swift 不允许直接使用 nil,需要通过可选类型来处理可能为空的值。使用 ? 符号来声明可选类型:

1
2
3
4
5
extension NSAttributedString {
init(string str: String?) {
// 初始化代码
}
}

返回可选类型的函数:

1
2
3
4
func parseColorFromHexString(input: String) -> UIColor? {
// 解析代码
return nil // 或返回 UIColor 实例
}

2. 值类型与引用类型

2.1 值类型

值类型在赋值和作为参数时都是复制的。值类型包括:

  • 数字
  • 字符串
  • 数组
  • 字典
  • 枚举
  • 元组
  • 结构体

示例:

1
2
3
4
var a = "Hello"
var b = a
b.append(", world")
print("a: \(a); b: \(b)") // 输出: a: Hello; b: Hello, world

2.2 引用类型

引用类型可以有多所有者,一般类都是引用类型:

1
2
3
4
var a = UIView()
var b = a
b.alpha = 0.5
print("a: \(a.alpha); b: \(b.alpha)") // 输出: a: 0.5; b: 0.5

3. 函数

3.1 标准函数

1
2
3
4
5
func hello(name: String, age: Int, location: String) {
print("Hello \(name). I live in \(location) too. When is your \(age + 1)th birthday?")
}

hello(name: "Mr. Roboto", age: 5, location: "San Francisco")

3.2 外部参数

外部参数名称可以解决调用函数时参数含义不明确的问题:

1
2
3
4
5
func hello(fromName name: String) {
print("\(name) says hello to you!")
}

hello(fromName: "Mr. Roboto")

如果需要外部参数和内部参数名相同,只需要在参数前加上 #

1
2
3
4
5
func hello(#name: String) {
print("hello \(name)")
}

hello(name: "Robot")

4. 类中的方法

4.1 标准参数

类中的方法参数调用和函数不同,第一个参数不被外部包含,后面的参数会被作为外部参数名:

1
2
3
4
5
6
7
8
class MyFunClass {
func helloWithName(name: String, age: Int, location: String) {
print("Hello \(name). I live in \(location) too. When is your \(age + 1)th birthday?")
}
}

let myFunClass = MyFunClass()
myFunClass.helloWithName(name: "Mr. Roboto", age: 5, location: "San Francisco")

如果不想显示外部参数名,可以通过添加 _ 解决:

1
2
3
4
5
6
7
8
class MyFunClass {
func helloWithName(name: String, _ age: Int, _ location: String) {
print("Hello \(name). I live in \(location) too. When is your \(age + 1)th birthday?")
}
}

let myFunClass = MyFunClass()
myFunClass.helloWithName(name: "Mr. Roboto", 5, "San Francisco")

4.2 初始化

初始化时第一个参数必须是外部的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct Celsius {
var temperatureInCelsius: Double

init(fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit - 32.0) / 1.8
}

init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin - 273.15
}

init(_ celsius: Double) {
temperatureInCelsius = celsius
}
}

let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
// boilingPointOfWater.temperatureInCelsius 是 100.0

let freezingPointOfWater = Celsius(fromKelvin: 273.15)
// freezingPointOfWater.temperatureInCelsius 是 0.0

let bodyTemperature = Celsius(37.0)
// bodyTemperature.temperatureInCelsius 是 37.0

4.3 可选参数

当参数是可选类型时,需要进行解包:

1
2
3
4
5
6
7
func processOptionalString(_ str: String?) {
if let unwrappedStr = str {
print("处理字符串: \(unwrappedStr)")
} else {
print("字符串为空")
}
}

语法参考

The Swift Programming Language》中文版:https://numbbbbb.gitbooks.io/-the-swift-programming-language-/