Swift基本语法(一)

本文介绍了Swift基本数据类型的使用,和与Objective-C语法的差别。另外,函数的基本语法,闭包(Closure)的基本语法,Closure与Function结合使用,以及一些需要注意的问题。

数据类型

元祖(Tuples)

Tuples可以把多个不同类型的值合成一个复合值。

1
2
3
4
5
6
7
8
9
10
11
12
// Tuple type
let httpStatus = (200, "success")
let httpErrorStatus = (404, "File not found")
//避免使用, 程序可读性较差
httpStatus.0
httpErrorStatus.1
//给每一个值起别名,使用名称访问
let personInfo = (name: "Tom", age: 20, sex: "男")
personInfo.name
personInfo.age
personInfo.sex

??

1
2
3
4
5
6
7
8
9
var nameString: String?
var nameStringD = nameString ?? "A default name"

//结果为: A default name

var nameString: String? = "Owenli"
var nameStringD = nameString ?? "A default name"
//结果为:Owenli

Range Operator

1
2
3
4
5
6
7
8
9
10
11
12
//: Close range Operator
//begin...end
for index in 1...5 {
print(index)
}
//输出:1 2 3 4 5

//begin..<end
for index in 1..<5 {
print(index)
}
//输出:1 2 3 4

Collections

Array

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
//: ### Collections 
//: Ordered colletion
//: Unordered colletion

//: ### Array

var array1: Array<Int> = Array<Int>()
var array2:[Int] = array1
var array3 = array1

var threeInts = [Int](count: 3, repeatedValue:1)
var sixInts = threeInts + threeInts

var fiveInts = [1, 2, 3, 4, 5]

//: Acess
//count
fiveInts.count

//Empty
if array2.isEmpty {
print("array2 is empty")
}

// Append
array1.append(1) //[1]
array2 += [2, 3 ,4]

// Indices
array2[2] //4

array2[0...1] //[2, 3]
array2[1...2] //[3, 4]
array2[0..<2] //[2, 3]
array2[0...1] = [5] //[5]
array2 //[5, 4]

//Insert and remove element at index
array2.insert(6, atIndex: 0)
array2.removeAtIndex(0)
array2
array2.removeLast()

//index and value
for (index , value) in fiveInts.enumerate() {
print("index : \(index); value:\(value)")
}

Set

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
let emptySet = Set<Character>()

let vowel: Set<Character> = ["a", "b", "c"]
var evenSet:Set = [2, 3, 4, 5]

//basic operator
vowel.count
emptySet.isEmpty
evenSet.insert(12)
evenSet.remove(12)
evenSet.contains(2)

for number in evenSet.sort() {
print(number)
}

for number in evenSet {
print(number)
}

//: Set operation
var setA: Set = [1, 2 , 3, 4 ,5 , 6]
var setB: Set = [4, 5, 6, 7, 8 , 9]

let interSectAB:Set = setA.intersect(setB)
let exculusiveAB:Set = setA.exclusiveOr(setB)
let unionAB:Set = setA.union(setB)
let aSubstractB = setA.subtract(setB)

var setC: Set = [1, 2, 3]

//超集
setA.isSupersetOf(setC)
//子集
setC.isSubsetOf(setA)

//
setA.isStrictSupersetOf(setC)
setC.isStrictSubsetOf(setA)

//无交集
setB.isDisjointWith(setC)

Dictionary

1
2
3
4
5
6
7
8
var initDictionary = [Int: String]()

var cityNumber = [
1: "beijing",
2: "shanghai",
3: "shandong"
]

数组操作与Objective-C相似。

Control Flow

for/while if

注意:条件不用加括号,另外if条件可以是表达式

Switch

注意:

  • switch条件不需要括号,内部不需要break,默认执行完一条语句跳出switch。如果不跳出需要使用fallthrogh修饰
  • case 可以匹配多个值,使用逗号隔开
  • case 进行区间匹配
  • default 必须写
  • 每个case必须要有一条语句

Function

函数参数

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
func printName() {
print("My name is Owenli")
}
printName()

//: #### Function param
// name Type
func multipleOfTen(multipler: Int) {
print("\(multipler) * 10 = \(multipler * 10)")
}
multipleOfTen(5)
// innerName -->multiplier
// outerName -->andValue
func multipleOf(multiplier: Int = 10, andValue: Int = 10) {
print("\(multiplier) * \(andValue) = \(multiplier * andValue)")
}
multipleOf()
multipleOf(5, andValue: 9)

//: Variadic param
func arraySum(number: Double...) {
var sum: Double = 0
for i in number {
sum += i
}
print("sum: \(sum)")
}
arraySum(1, 2, 4 ,5 , 6)

//: 函数内部修改参数值
func increment(inout value: Int) {
value += 1
}
var m = 10
increment(&m)

注意:

  • 函数内部修改参数需要使用inout修饰,并且在调用时传递指针。
  • 函数参数 可以不限个数
  • 函数参数 innerName, outerName。 outerName是为了方便程序阅读。

函数返回值

函数返回值:单个值,多个值,Optional类型, 函数类型

1
2
3
4
5
6
7
8
9
10
11
12
//带返回值的函数
func multipleOf1(multiplier: Int = 10, andValue: Int = 10) -> Int {
return multiplier * andValue
}
multipleOf1()

//组合参数
func tableInfo() -> (row: Int, column: Int) {
return (4 , 5)
}
var table = tableInfo()

Optional类型

1
2
3
4
5
6
7
8
//返回一个Optional类型
func string2Int(str: String) -> Int? {
return Int(str)
}

var n = string2Int("123")
n.dynamicType //这是 Optional<Int>.Type

函数类型

1
2
3
4
5
6
7
8
9
10
var f1: (Int, Int) -> Int = multipleOf1 
var f2 = tableInfo
var f3 = string2Int

//参数中使用函数类型
func execute(fn:(String) -> Int?, _ fnParam: String) {
fn(fnParam)
}
execute(f3, "123")

内嵌函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
typealias op = (Int) -> Int //重命名

func whichOne(n: Bool) -> op {

func increment(n: Int) -> Int {
return n + 1
}
func decrement(n: Int) -> Int {
return n - 1
}

return n ? increment : decrement
}

var one = 1
var oneToTen = whichOne(one < 10)

while one < 10 {
one = oneToTen(one)
}

Closures(闭包)

闭包是自包含函数代码块,可以在代码中被传递和使用。Swift中的闭包同Objective-C中的(block)以及其他一些编程语言的匿名函数比较相似。闭包可以捕获起所在上下文中任意变量和常量的引用。

1
2
3
4
5
6
7
8
9
10
11
//定义完整的Closure
var addClosure: (Int, Int) -> Int = { (a: Int, b:Int) -> Int in
return a + b
}
addClosure(5, 10)

//简化
addClosure = {a, b in return a + b }
addClosure = {a, b in a + b} //Single expression closure
// $0, 1, 2 代替a, b
addClosure = {$0 + $1}
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
//闭包做参数
func executeClosure(a: Int, _ b:Int, operation: (Int, Int) ->Int) -> Int {
return operation(a, b)
}

func addFunc(a:Int, _ b: Int) -> Int {
return a + b
}

executeClosure(1, 10, operation: addFunc)

executeClosure(1, 10, operation: addClosure)


//简化
executeClosure(1, 10, operation: {(a: Int, b: Int) -> Int in
return a + b
})

executeClosure(1, 10, operation: {a , b in a + b})

executeClosure(1, 10, operation: {$0 + $1})

executeClosure(1, 10){$0 + $1} // Trailing Closure 尾随闭包

//void
let voidClosure:() -> Void = {}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//capturing values 捕获变量
var count = 0
let incrementCount = { ++count }
incrementCount() //1
incrementCount() //2
incrementCount() //3
incrementCount() //4


func counting() -> () -> Int {
var count = 0
let incrementCoun: () -> Int = { ++count }
return incrementCoun
}
let c1 = counting()
c1() //1
c1() //2

参考资料

  1. 简阅Swift - 遇见每一个似曾相识的技术
  2. Swift学习资料Github总结
  3. The Swift Programming Language 2.0 中文版