理解Swift 闭包,还是看Xcode自带的Documentation好

Understand the Results of Synchronous and Asynchronous Calls
When you pass a closure to an API, consider when that closure will be called relative to the other code in your app. In synchronous APIs, the result of calling the closure will be available immediately after you pass the closure. In asynchronous APIs, the result won't be available until sometime later; this difference affects how you write code both in your closure as well as the code following your closure.
The example below defines two functions, now(:) and later(:). You can call both functions the same way: with a trailing closure and no other arguments. Both now(:) and later(:) accept a closure and call it, but later(_:) waits a couple seconds before calling its closure.
import Dispatch
let queue = DispatchQueue(label: "com.example.queue")

func now(_ closure: () -> Void) {
    closure()
}

func later(_ closure: @escaping () -> Void) {
    queue.asyncAfter(deadline: .now() + 2) {
        closure()
    }
}

The now(:) and later(:) functions represent the two most common categories of APIs you'll encounter in methods from app frameworks that take closures: synchronous APIs like now(:), and asynchronous APIs like later(:).

也许我们看过无数次关于闭包的定义和实例,但苹果给的解析是我看过最清晰的,同步闭包和异步闭包。
要想异步闭包生效,必须在加上@escaping

你可能感兴趣的:(理解Swift 闭包,还是看Xcode自带的Documentation好)