gpt4 book ai didi

swift - 调用以 TypeAlias 作为参数的函数?

转载 作者:搜寻专家 更新时间:2023-11-01 06:19:20 25 4
gpt4 key购买 nike

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

最佳答案

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

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

关于swift - 调用以 TypeAlias 作为参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37244576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com