简体   繁体   English

如何将闭包提取为类型别名?

[英]How to extract a closure into typealias?

I'm a bit lost with typealias, the following chunk of code works fine, which I would like to refactor into using typealias. 我对typealias有点迷惑,下面的代码块工作正常,我想将其重构为使用typealias。

NEVPNManager.shared().loadFromPreferences(completionHandler: vpnLoadHandler)

func vpnLoadHandler(_: (Error?)) -> Void {

}

I would like to create a typealias instead: 我想创建一个类型别名:

typealias vpnCompleteClosure = (_: (Error?)) -> Void

func vpnLoadHandler(complete: @escaping vpnCompleteClosure) {
}

NEVPNManager.shared().loadFromPreferences(completionHandler: vpnLoadHandler)

Unfortunately this doesn't compile anymore: 不幸的是,这不再编译了:

Cannot convert value of type '(@escaping vpnCompleteClosure) -> ()' (aka '((Optional) -> ()) -> ()') to expected argument type '(Error?) -> Void' 无法将类型'(@escaping vpnCompleteClosure)->()'(aka'(((Optional)->())->()')的值转换为预期的参数类型'(Error?)-> Void'

What am I missing? 我想念什么?

UPDATE: 更新:

open func loadFromPreferences(completionHandler: @escaping (Error?) -> Swift.Void)

loadFromPreferences(completionHandler:) is expecting a parameter, completion that is of type (Error?) -> Void Your typealias is passing a ((Optional) -> Void) -> Void Your error is telling you you have mismatching signatures. loadFromPreferences(completionHandler:)期待一个参数, completion即类型的(Error?) -> Voidtypealias传递的是((Optional) -> Void) -> Void您的错误是告诉你,你有不匹配的签名。

That being said, you need to figure out what the signature of the top level method is. 就是说,您需要弄清楚顶级方法的签名是什么。 What are you calling your completionHandler on? 您在打电话给您的completionHandler吗? What are you expecting to get back from it. 您期望从中得到什么。

I have to admit Im confused as to your purpose of passing vpnLoadHandler(complete:) into loadFromPreferences(completionHandler:) 我不得不承认我对于将vpnLoadHandler(complete:)传递到loadFromPreferences(completionHandler:)目的感到困惑

Your method will end up looking like (((Error?)-> Void) -> Void) -> Void 您的方法最终看起来像(((Error?)-> Void) -> Void) -> Void

write your typealias as: 将您的typealias写为:

 typealias VPNCompletionHandler = (Error?) -> Void

 func vpnLoadHandler(completion: @escaping VPNCompletionHandler)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM