使用闭包进行异步编码

闭包通常用于异步任务,例如从网站获取数据时。

Version < 3.0

func getData(urlString: String, callback: (result: NSData?) -> Void) {

    // Turn the URL string into an NSURLRequest.
    guard let url = NSURL(string: urlString) else { return }
    let request = NSURLRequest(URL: url)
    
    // Asynchronously fetch data from the given URL.
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {(data: NSData?, response: NSURLResponse?, error: NSError?) in

        // We now have the NSData response from the website.
        // We can get it "out" of the function by using the callback 
        // that was passed to this function as a parameter.

        callback(result: data)
    }
        
    task.resume()
}

此函数是异步的,因此不会阻止调用它的线程(如果在 GUI 应用程序的主线程上调用,它将不会冻结接口)。

Version < 3.0

print("1. Going to call getData")

getData("http://www.example.com") {(result: NSData?) -> Void in

    // Called when the data from http://www.example.com has been fetched.
    print("2. Fetched data")
}

print("3. Called getData")

因为任务是异步的,所以输出通常如下所示:

"1. Going to call getData"
"3. Called getData"
"2. Fetched data"

因为在获取 URL 中的数据之前,不会调用闭包内的代码 print("2. Fetched data")