Swift初探

特性

允许类似Python的无main函数语法、terminal中执行(swift repl)、语句结尾无分号。

基本语法

简单值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
* let:声明常量
* var:声明变量
*/
var myVariable = 42
myVariable = 50
let myConstant = 42

// 如果初始值没有提供足够的信息(或者没有初始值),则需要在变量后面声明类型,用冒号分割。
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70

// 值永远不会被隐式转换为其他类型。如果你需要把一个值转换成其他类型,请显式转换。
let label = "The width is "
let width = 94
let widthLabel = label + String(width) // 删去String()会报错

// 有一种更简单的把值转换成字符串的方法:把值写到括号中,并且在括号之前写一个反斜杠(\)。
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."

// 使用三个双引号(""")来包含多行字符串内容。每行行首的缩进会被去除,只要和结尾引号的缩进相匹配。
let quotation = """
I said "I have \(apples) apples."
And then I said "I have \(apples + oranges) pieces of fruit."
"""

// 使用方括号 [] 来创建数组和字典,并使用下标或者键(key)来访问元素。最后一个元素后面允许有个逗号。
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

// 数组在添加元素时会自动变大。
shoppingList.append("blue paint")
print(shoppingList)

// 使用初始化语法来创建一个空数组或者空字典。
let emptyArray: [String] = []
let emptyDictionary: [String: Float] = [:]

// 如果类型信息可以被推断出来,你可以用 [] 和 [:] 来创建空数组和空字典——比如,在给变量赋新值或者给函数传参数的时候。
shoppingList = []
occupations = [:]

控制流

分支

分支结构有:ifswitch

循环

循环结构有:for-inwhilerepeat-while

函数

1
2
3
func funcName(){
// ...
}

注释

1
2
3
4
5
// comment

/*
comments
*/

数据

均用小端存储。不需要做大小端转换。Official note

.jpg

Ref

Swift Book 中文