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"]