Swift 闭包(带有默认值)作为函数参数

Swift 闭包(带有默认值)作为函数参数,swift,swift3,closures,default-parameters,Swift,Swift3,Closures,Default Parameters,感谢斯威夫特的奇迹,我们可以: func someFunction(someParameter: someType, someOtherParameter: someOtherType) 我们这样称呼它: someFunction(x, y) func someFunction(someParameter: someType, completionClosure: @escaping () -> ()? = nil) 我们还有: func someFunction(someParam

感谢斯威夫特的奇迹,我们可以:

func someFunction(someParameter: someType, someOtherParameter: someOtherType)
我们这样称呼它:

someFunction(x, y)
func someFunction(someParameter: someType, completionClosure: @escaping () -> ()? = nil)
我们还有:

func someFunction(someParameter: someType, someOtherParameter: someOtherType?)
我们可以这样称呼它:

someFunc(x, y)

然而,零在那里看起来“丑陋”。更不用说我们是否有多个可选参数:它看起来

someFunc(x, nil, nil, nil,...etc)
恐怖

因此,我们可以这样写:

func someFunction(someParameter: someType, someOtherParameter: someOtherType? = nil)
现在,我们可以很好地说:

someFunction(x, y)

现在…问题是:我想要上面所有的机制,但“y”必须是一个闭包。 一个死气沉沉的人。没有输入参数,没有返回类型。()->()类。 我还希望它是可选的(我可以提供也可以不提供),我希望它用nil初始化,这样如果我没有提供闭包,我就可以完全忽略该参数

所以:我想说

someFunction(x, { ... }) 

为此,我宣布如下:

someFunction(x, y)
func someFunction(someParameter: someType, completionClosure: @escaping () -> ()? = nil)
然而,编译器不会有任何这些。基本上它说:

发生什么事了




该主题已关闭-->重复的

但第一个问题大部分仍未得到回答/解决,而第二个问题似乎主要围绕着“逃避问题”

本主题的主题是关于()->()?=零分。简单地删除@escaping(如第二部分所述)并不能解决问题;事实上,它引入了一个新概念:

在另一位同事的建议下,问题在@autoclosure的帮助下得到了解决

func someFunction(someParameter: someType, completionClosure: @escaping @autoclosure () -> ()? = nil)
现在它按预期构建/运行

我并不认为我完全理解@autoclosure是如何解决这个问题的(即使在我的同事解释之后,在我自己的研究之后;我已经提供了一个……好吧……关闭……为什么要依赖自动生成的关闭……),但现在我不得不继续进行功能开发。我以后会再谈这个问题。 同时,如果其他人能照亮它,请放心

func someFunction(someParameter: someType, completionClosure: @escaping @autoclosure () -> ()? = nil)