![](/img/trans.png)
[英]Passing closure in swift as parameter to be used by selector in function
[英]SWIFT: Passing variable from closure to function
我正在嘗試創建一個返回NSDictionary的函數,而該函數又需要從閉包中返回。
我是Swift的新手,在解決這一問題時遇到了問題。 任何幫助將不勝感激。
// Takes a String, needs to return a NSDictionary
func login(action: String) -> NSDictionary
{
let command = NSURL(string: "\(connectionType)://\(url)/includes/api.php?username=\(username)&password=\(password)&accesskey=\(apiKey)&action=\(action)&responsetype=json")
print(command!)
let session = NSURLSession.sharedSession()
// Get error here when changing Void > NSDictionary
let task = session.dataTaskWithURL(command!) {
(data, response, error) -> Void in
if error != nil {
print(error!.localizedDescription)
} else {
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary
print(result) // Need this returned
} catch {
// handle error
print(error)
}
}
}
task.resume()
return result As! NSDictionary // returns empty, because of -> Void??
}
問題在於dataTaskWithURL
是一個異步函數,因此在返回該函數之前還沒有執行該塊。
您需要做的是設置一個可以在self
上調用的函數,該函數將在模塊執行后告知self
並可以將結果傳遞給您,或者設置一個帶有委托的協議,您可以調用該協議以通知結果
同樣, -> Void
在塊內是塊的返回類型,您實際上不應該在該塊內返回任何東西,因為父函數不希望返回任何東西,因此實際上不會發生任何事情,因此為什么要返回Void
在您聲明閉包的類型時
let task = session.dataTaskWithURL(command!) {
(data, response, error) -> Void in
/* closure body */
}
將Void
更改為JSONObject
。 但這還不是全部! 您試圖從登錄函數返回一些信息,這些信息會進行異步調用,而這是不可能的。 取而代之的是,您的login
函數本身需要使用閉包,而閉包將是您對結果NSDictionary
。 因此,將您的login
聲明更改為
func login(action: String, completionHandler: (NSDictionary) -> ())
並相應地實現completionHandler
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.