如何创建与 @escaping 一起使用的闭包

发布于 2025-01-10 18:36:15 字数 1043 浏览 3 评论 0原文

我在委托上有这个函数签名,

func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:])

我需要在单例上创建一个闭包来转发该委托方法,然后我这样做:

typealias sessionDidReceiveUserInfoHandler = (WCSession, [String : Any]) -> Void
var sessionDidReceiveUserInfo: sessionDidReceiveUserInfoHandler?

然后像这样使用它:

let mySingleton = MySingleton.sharedInstance
mySingleton.sessionDidReceiveUserInfo = {(session, userInfo) in }

现在我有这个带有 @escaping 子句

func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {

我该如何为该签名执行此操作。 Xcode 不会让我像这样将转义添加到类型别名中:

typealias sessionDidReceiveMessageReplyHandlerHandler = (WCSession, [String : Any], @escaping ([String : Any])) -> Void

如果我创建一个没有转义的类型别名,它不会让我在带有错误消息的函数内部使用

无法转换 '([String : Any]) 类型的值 ->预期无效 参数类型“[String:Any]”

I have this function signature on a delegate

func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:])

I need to create a closure on a Singleton to forward that delegate method, then I do this:

typealias sessionDidReceiveUserInfoHandler = (WCSession, [String : Any]) -> Void
var sessionDidReceiveUserInfo: sessionDidReceiveUserInfoHandler?

and I use it like this:

let mySingleton = MySingleton.sharedInstance
mySingleton.sessionDidReceiveUserInfo = {(session, userInfo) in }

Now I have this function signature with the @escaping clause

func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {

How do I do that for that signature. Xcode will not let me to add the escaping to the typealias like this:

typealias sessionDidReceiveMessageReplyHandlerHandler = (WCSession, [String : Any], @escaping ([String : Any])) -> Void

and if I create a typealias without the escaping it will not let me use inside the function with the error message

Cannot convert value of type '([String : Any]) -> Void' to expected
argument type '[String : Any]'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萝莉病 2025-01-17 18:36:15

您缺少闭包上的返回类型(即在最后一个 ) 内):

typealias sessionDidReceiveMessageReplyHandlerHandler = (WCSession, [String : Any], @escaping ([String : Any]) -> Void) -> Void

You're missing a return type on the closure (ie inside the last )):

typealias sessionDidReceiveMessageReplyHandlerHandler = (WCSession, [String : Any], @escaping ([String : Any]) -> Void) -> Void
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文