簡體   English   中英

Swift中的完成處理程序

[英]Completion Handler in Swift

我一直在尋找很多小時試圖在swift中找到解決這個閉包問題的方法。 我找到了很多資源來解釋閉包但由於某種原因我似乎無法使其工作。

這是我試圖轉換為swift的Objective-C代碼:

[direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
            NSLog(@"%@",[response description]);
            NSLog(@"%@",[error description]);

            }];

我正在嘗試但是沒有工作:

directions.calculateDirectionsWithCompletionHandler(response: MKDirectionsResponse?, error: NSError?) {
    println(response.description)
    println(error.description)
}

directions是一個MKDirections對象。

謝謝!

嘗試

directions.calculateDirectionsWithCompletionHandler ({
(response: MKDirectionsResponse?, error: NSError?) in 
        println(response?.description)
        println(error?.description)
    })

在此輸入圖像描述

這是Swift中塊/閉包的一般方式。

如果您不需要使用參數,您可以這樣做

directions.calculateDirectionsWithCompletionHandler ({
(_) in 
  // your code here
    })

關於SwiftClosures的語法,以及檢查MKDirections類參考:

在此輸入圖像描述

它看起來正確的閉包應該是一個MKDirectionHandler ,定義為:

在此輸入圖像描述

因此, 完成處理程序應如下所示:

direction.calculateDirectionsWithCompletionHandler( { (response: MKDirectionsResponse!, error: NSError!) -> () in
    println(response.description)
    println(error.description)
    } )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM