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. 直接将闭包定义在函数的参数中
repeatTask(times: 1, task: { () -> Void in
print("Swift Apprentice is a great book!")
})
3. 简化参数和返回值
repeatTask(times: 1, task: {
print("Swift Apprentice is a great book!")
})
4. 利用尾部闭包的特性,将参数名舍弃,并将闭包移到括号外部,这个是我们最常用的方式。
repeatTask(times: 1) {
print("Swift Apprentice is a great book!")
}
//方法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. 调用方法1
mathSum(length: 10) { number in
number * number
}
//2.调用方法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]
]
//先求平均数
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
//过滤、输出
let goodApps = averageRatings.filter {
$0.value > 3
}.map {
$0.key
}