swift 學習(4)閉包 (Closure)

1,閉包 (Closure)

Closures are so named because they have the ability to “close over” the variables and constants within the closure’s own scope. This simply means that a closure can access, store and manipulate the value of any variable or constant from the surrounding context. Variables and constants within the body of a closure are said to have been captured by the closure.

閉包可以理解為是一個沒有方法名的方法。形狀類似于:

(parameterList) -> returnType

(參數列表) -> 返回值類型

如何創建

var multiplyClosure: (Int, Int) -> Int

multiplyClosure = { (a: Int, b: Int) -> Int in
    return a * b
}

multiplyClosure = { (a, b) in
    a*b
}

multiplyClosure = {
    $0 * $1
}
let result = multiplyClosure(3, 2)
print(result)

尾隨閉包

func operateOnNumbers(_ a: Int, _ b: Int,
                      operation: (Int, Int) -> Int) -> Int {
    let result = operation(a, b)
    print(result)
    return result
}
//正常調用
operateOnNumbers(2, 21, operation: {
    (a:Int,b:Int) ->Int in a * b
})
//正常調用
operateOnNumbers(2, 21, operation: multiplyClosure)

//尾隨閉包 帶參數實現
operateOnNumbers(2, 21){ (a:Int,b:Int) -> Int in
    a * b
}
//尾隨閉包
operateOnNumbers(2, 21){
    $0 * $1
}

使用閉包進行自定義排序


let names = ["ZZZZZZ", "BB", "A", "CCCcccccccC", "EEEEE"]
//基本用法
names.sorted()

//自定義排序算法
names.sorted {
    $0.characters.count > $1.characters.count
}

sorted 函數

public func sorted(by areInIncreasingOrder: (Element, Element) -> Bool) -> [Element]

其中(Element, Element) -> Bool 閉包

swift中大量的使用了這種閉包的語法,可以使開發人員方便的自定義方法。

使用閉包進行迭代

var prices = [1.5, 10, 4.99, 2.30, 8.19]

let largePrices = prices.filter { (a) -> Bool in
    a > 5
}
let largePrices01 = prices.filter {
    return $0 > 5
}
public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]

let listArray = ["你好,","我是","你的","益達"];
let nomal0 = listArray.reduce("", {(a : String,b : String) -> String in return a + b})
print("nomal0 = \(nomal0)")

let nomal1 = listArray.reduce("", {(a : String,b : String) -> String in a + b})
print("nomal1 = \(nomal1)")

let nomal2 = listArray.reduce("", {(a,b) in a + b})
print("nomal2 = \(nomal2)")

let nomal3 = listArray.reduce("") {
    (a,b) in a + b
}
print("nomal3 = \(nomal3)")
let nomal4 = listArray.reduce("") {
    $0 + $1
}
print("nomal4 = \(nomal4)")

上述方法結果一樣。

let namesAndAges = ["Yunis":28,"Yunlia":18,"Tom":13,"Jack":8,"King":15]
let lessThan18 = namesAndAges.filter {
    return $0.value < 18
}
print(lessThan18)//[("Jack", 8), ("Tom", 13), ("King", 15)]

let namesList = lessThan18.map {
    return $0.key
}
print(namesList)//["Jack", "Tom", "King"]
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 以下翻譯自Apple官方文檔,結合自己的理解記錄下來。翻譯基于 swift 3.0.1 原文地址 Closure...
    藝術農閱讀 1,616評論 0 3
  • 四季如瘋的天氣 斷崖式的降溫… 風大好似臺風過境一般。 連同我的心情也郁郁寡歡。 情不能入心、 業不能合意、 沉悶...
    Yuki00閱讀 154評論 0 0
  • 今天休息,和男票的同事們一起出去燒烤。總體心情不錯。有點累,從下午回來一直在看爸爸去哪兒。有一個地方挺感動的,就是...
    清清小河y閱讀 151評論 0 1