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