Swift 3可选的转义闭包参数 [英] Swift 3 optional escaping closure parameter

查看:1655
本文介绍了Swift 3可选的转义闭包参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定:

typealias Action = () -> ()

var action: Action = { }

func doStuff(stuff: String, completion: @escaping Action) {
    print(stuff)
    action = completion
    completion()
}

func doStuffAgain() {
    print("again")
    action()
}

doStuff(stuff: "do stuff") { 
    print("swift 3!")
}

doStuffAgain()

有什么原因才能使完成参数并保留 @escaping 操作 ?

Is there any why to make the completion parameter (and action) of type Action? and also keep @escaping ?

更改类型会产生以下错误:

Changing the type gives the following error:

错误:@escaping属性仅适用于函数类型

删除 @escaping 属性,运行,但似乎不正确,因为完成闭包是转义函数的作用域。

Removing the @escaping attribute, the code compiles and runs, but doesn't seem to be correct since the completion closure is escaping the scope of the function.

推荐答案

有一个 SR-2552 报告 @escaping 无法识别函数类型别名。这就是为什么错误 @escaping属性只适用于函数类型。您可以通过扩展函数签名中的函数类型来解决:

There is a SR-2552 reporting that @escaping is not recognizing function type alias. that's why the error @escaping attribute only applies to function types. you can workaround by expanding the function type in the function signature:

typealias Action = () -> ()

var action: Action? = { }

func doStuff(stuff: String, completion: (@escaping ()->())?) {
    print(stuff)
    action = completion
    completion?()
}

func doStuffAgain() {
    print("again")
    action?()
}

doStuff(stuff: "do stuff") {
    print("swift 3!")
}

doStuffAgain()

编辑:

实际上在xcode 8测试版下,其中的错误 SR-2552 尚未解决。修复这个bug,介绍一个新的(你面临的),仍然是开放的。请参阅 SR-2444

I was actually under a xcode 8 beta version where the bug SR-2552 was not resolved yet. fixing that bug, introduced a new one(the one you're facing) that is still open. see SR-2444.

指向临时解决方案的解决方法是从可选的函数类型中删除 @escaping 属性,将函数保留为转义。

The workaround Michael Ilseman pointed as a temporary solution is remove the @escaping attribute from optional function type, that keep the function as escaping.

func doStuff(stuff: String, completion: Action?) {...}

这篇关于Swift 3可选的转义闭包参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆