斯坦福iOS9公开课总结三:More Swift
斯坦福iOS9公开课总结三:More Swift
镇长之前整理过一篇关于Swift基础知识的文章《Swift Tutorial》。本文是在这个文章的基础上补充Swift其他知识点。内容比较基础。
More Swift
Array
1
2
3var a = Array<String>()
//... is the same as ...
var a = [String]()注意:数组越界,数组遍历,不可变数组等问题。
Array<T> methods
filter(includeElement:(T) -> Bool) ->[T]
返回一个新的数组,满足给定谓词的要求。1
2let bigNumbers = [2, 47, 118, 5, 9].filter({$0 > 20})
//bigNumber = [47, 118]map(transform:(T) ->U) -> [U]
通过映射关系创建一个新的数组。1
2let stringified: [String] = [1, 2, 3].map{String($0)}
//stringified = ["1", "2", "3"]reduce(initial: U, combine: (U, T) -> U) -> U
:
1
2
3
4
5
6let sum: Int = [1, 2, 3].reduce(0){$0 + $1}
// 得到数组元素和。 sum = 6
//0: 代表sum的默认值
//另外写法
let add:(Int, Int) -> Int = {x, y in x + y}
let sum: Int = [1, 2, 3].reduce(0, add)Dictionary
1
2
3
4
5
6
7var pic = Dictionary<String, Int>()
var pic1 = [String: Int]()
pic = ["one": 1,"Two": 2]
let three = pic["three"] //three is Optional Int
for (key, value) in pic {
print("\(key) = \(value)")
}
小结
本节视频讲解了Swift基本语法内容。