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

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

问题描述

给出:

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

有什么方法可以使Action?类型的completion参数(和action)并保持@escaping吗?

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

更改类型会出现以下错误:

Changing the type gives the following error:

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

@escaping attribute only applies to function types

删除@escaping属性后,代码将编译并运行,但是由于completion闭包正在转义函数的范围,因此似乎并不正确.

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 attribute only applies to function types的原因.您可以通过扩展函数签名中的函数类型来解决:

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 beta版本下,其中的错误 SR-2552 是尚未解决.修复了该错误,引入了一个仍未解决的新错误(您面临的错误).参见 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.

作为临时解决方案的解决方法 @Michael Ilseman 是从可选函数类型中删除@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?) {...}

:

SR-2444 已关闭,明确指出参数位置不是转义的,并且需要用@escaping标记它们以使其转义,但是可选参数的隐式转义,因为((Int)->())?Optional<(Int)->()>的同义词,可选的闭包正在转义.

The SR-2444 has been closed stating explicitly that closures in parameters positions are not escaping and need them to be marked with @escaping to make them escaping, but the optional parameters are implicitly escaping, since ((Int)->())? is a synonyms of Optional<(Int)->()>, optional closures are escaping.

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

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