所以我写了一个与闭包有关的练习程序。我试图更好地理解异步概念的工作原理。当我尝试拨打request()
时,我会收到转换错误,如下所示:
import UIKit
let correctPasscode = "3EyX"
typealias CompletionHandler = (result: AnyObject?, error: String?) -> Void
func request(passcode: String, completionHandler: CompletionHandler) {
sendBackRequest(passcode) {(result, error) -> Void in
if error != nil {
print(error)
}
else {
print(result)
}}
}
func sendBackRequest(passCode: String, completionHandler: CompletionHandler) {
if passCode == correctPasscode {
completionHandler(result: "Correct. Please proceed", error: nil)
} else {
completionHandler(result: nil, error: "There was an error signing in")
}
}
request(correctPasscode, completionHandler: CompletionHandler) // Error happens here
答案 0 :(得分:3)
类型别名可以告诉您需要传递的实际类型。在这种情况下,类型是类型的闭包
你这样传递: 甚至更短 - 或甚至更短 - (这些类型通过func声明已知) - (result: AnyObject?, error: String?) -> Void
request(correctPasscode, completionHandler:{
(result: AnyObject?, error: String?) in
print("Inside the handler...")
// Do some useful things here
})
request(correctPasscode) {
(result: AnyObject?, error: String?) in
print("Inside the handler...")
// Do some useful things here
}
request(correctPasscode) { result, error in
print("Inside the handler...")
// Do some useful things here
}
答案 1 :(得分:1)
我不确定你想要完成什么,但这一行:
request(correctPasscode, completionHandler: CompletionHandler)
无法编译,因为您没有将CompletionHandler
闭包传递给函数,而是传递 type 对象,表示该完成处理程序的类型。
因此错误:Cannot convert value of 'CompletionHandler.*Type*'
。
有效的通话将是:
request(correctPasscode) { result, error in
print("result was \(result), and error was \(error)")
}
但是你的request
函数对传入的闭包没有任何作用。有点难以说出你想要的东西......