Swift4 Closure 閉包練習(xí)

  • repeatTask
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
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容