调用具有TypeAlias作为参数的函数?

时间:2016-05-15 22:58:38

标签: swift asynchronous closures

所以我写了一个与闭包有关的练习程序。我试图更好地理解异步概念的工作原理。当我尝试拨打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

enter image description here

2 个答案:

答案 0 :(得分:3)

类型别名可以告诉您需要传递的实际类型。在这种情况下,类型是类型的闭包

(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
}

或甚至更短 - (这些类型通过func声明已知) -

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函数对传入的闭包没有任何作用。有点难以说出你想要的东西......