map基本使用方法:
var xa = [1,2,3]
let squares =xa.map {
$0 * $0
}
等价于:var squares = [Int]()
for e inxa {
squares.append(e * e)
}
map的实现方法:
extension Array {
func map_wershest<T>(_ transform:(Element)->T) -> [T] {
var result: [T] = []
result.reserveCapacity(count)
forxinself {
result.append(transform(x))
}
return result
}
}
let cubes = x.map_wershest {
$0 * $0 * $0
}
不禁回想起十多年前,第一次遇见C++标准库,一脸懵x。硬着头皮看了几眼,掉头就走,再也没有回去过。如此简单的“套路”,居然成为了大名鼎鼎的 map-reduce。现在想想,当时只是少了一点点耐心,再加上英语单词背的太少,无法找到循序渐进的书籍,由浅入深的把它学透。以至于,与如此简单而神奇的代码,错过了十多年。感谢万能的Internet,如今我们可以轻易的薅资本主义羊毛:<Eloquent javaScript, 2nd Edition> (safaribooksonline.com), Chapter 5. Higher-Order Functions<Mastering Swift 3> (safaribooksonline.com), Chapter 3. Using Swift Collections and the Tuple Type<Advanced Swift> Chapter 1 Built-In Collections新闻热点
疑难解答