func repeatTask(times: Int, task: () -> Void) {
for _ in 0..<times {
task()
}
}
let task = {
print("Swift Apprentice is a great book!")
}
1. 最原始的方式
repeatTask(times: 1, task: task)
2. 直接將閉包定義在函數(shù)的參數(shù)中
repeatTask(times: 1, task: { () -> Void in
print("Swift Apprentice is a great book!")
})
3. 簡(jiǎn)化參數(shù)和返回值
repeatTask(times: 1, task: {
print("Swift Apprentice is a great book!")
})
4. 利用尾部閉包的特性,將參數(shù)名舍棄,并將閉包移到括號(hào)外部,這個(gè)是我們最常用的方式。
repeatTask(times: 1) {
print("Swift Apprentice is a great book!")
}
數(shù)學(xué)計(jì)算
//方法1
func mathSum(length: Int, series: (Int) -> Int) -> Int {
var result = 0
for i in 1...length {
result += series(i)
}
return result
}
//方法2
func mathSum(length: Int, series: (Int) -> Int) -> Int {
return (1...length).map { series($0) }.reduce(0, +)
}
//1. 調(diào)用方法1
mathSum(length: 10) { number in
number * number
}
//2.調(diào)用方法2
mathSum(length: 10) {
$0 * $0
}
字典處理
let appRatings = [
"Calendar Pro": [1, 5, 5, 4, 2, 1, 5, 4],
"The Messenger": [5, 4, 2, 5, 4, 1, 1, 2],
"Socialise": [2, 1, 2, 2, 1, 2, 4, 2]
]
//先求平均數(shù)
var averageRatings: [String: Double] = [:]
appRatings.forEach {
let total = $0.value.reduce(0, +) // + is a function too!
averageRatings[$0.key] = Double(total) / Double($0.value.count)
}
averageRatings
//過(guò)濾、輸出
let goodApps = averageRatings.filter {
$0.value > 3
}.map {
$0.key
}