# Swift 闭包学习笔记

**URL:** <https://www.shiqidu.com/t/topic/629>\
**Category:** 开发调优\
**Tags:** Swift\
**Created:** [2019 年8 月 22 日 02:45 UTC](https://www.shiqidu.com/t/topic/629 "2019-08-22T02:45:44Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![Leon](https://www.shiqidu.com/user_avatar/www.shiqidu.com/leon/32/5_2.png) [@Leon](https://www.shiqidu.com/u/Leon)\
发布日期： [2019 年8 月 22 日 02:45 UTC](https://www.shiqidu.com/t/topic/629/1 "2019-08-22T02:45:44Z")

</div>

### 闭包语法

```auto
{(params) -> (returnType) in statements}

```

字符串数组

```swift
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]

```

### 常规写法

```swift
func backward(_ s1: String, _ s2: String) -> Bool {
    return s1 > s2
}
var reversedNames = names.sorted(by: backward(_:_:))

```

#### 逐渐简化

```swift
reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in return s1 > s2 } )

```

因为Swift可以自动推断形参类型和返回类型, 所以可以这样写

```swift
reversedNames = names.sorted(by: { s1, s2 in return s1 > s2} )

```

单表达式闭包可以隐藏 return

```swift
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )

```

Swift 自动对行内闭包提供简写实际参数名，你也可以通过 $0 , $1 , $2 等名字来引用闭包的实际参数值。

```swift
reversedNames = names.sorted(by: { $0 > $1 } )

```

Swift 的 String 类型定义了关于大于号（ \>）的特定字符串实现，

```swift
reversedNames = names.sorted(by: >)

```

### 尾随闭包

```swift
// 闭包可以写在方法外面
reversedNames = names.sorted() { $0 > $1 }
// 如果闭包作为唯一的实际参数被传入,可以不需要 () 圆括号
reversedNames = names.sorted {$0 > $1}

```

**将数字数组变成对应的字符串数组**

```swift
let digitNames = [
    0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
    5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine",
]

let numbers = [16, 58, 510]

let strings = numbers.map {
    (number) -> String in
    var number = number
    var output = ""
    repeat {
        output = digitNames[number % 10]! + output
        number /= 10
        print(output + ",")
    } while number > 0
    return output
}

print(strings)
// 输出 ["OneSix", "FiveEight", "FiveOneZero"]

```

### 逃逸闭包

当闭包作为一个实际参数传递给一个函数的时候，我们就说这个闭包逃逸了，因为它可以在函数返回之后被调用。当你声明一个接受闭包作为形式参数的函数时，你可以在形式参数前写 @escaping 来明确闭包是允许逃逸的。

```swift
var completionHandlers: [() -> Void] = []
func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) {
    completionHandlers.append(completionHandler)
}

func someFunctionWithNonescapingClosure(closure: () -> Void) {
    closure()
}
 
class SomeClass {
    var x = 10
    func doSomething() {
        someFunctionWithEscapingClosure { self.x = 100 }
        someFunctionWithNonescapingClosure { x = 200 }
    }
}
 
let instance = SomeClass()
instance.doSomething()
print(instance.x)
// Prints "200"
 
completionHandlers.first?()
print(instance.x)
// Prints "100"

```
