使用閉包進行非同步編碼

閉包通常用於非同步任務,例如從網站獲取資料時。

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