首页 > 解决方案 > 是否可以在闭包中使用可变参数?

问题描述

翻新问题

Swift:结合使用可变参数和闭包


是否可以使用可变参数进行闭包?

func this(_ hello: (Int...) -> ()) {}
func that(_ yeah: Int...) {}

以下是有效的:this(that)
以下是无效的: this { foo in }, this { _ in },this { }


我收到此错误:
Cannot convert value of type '(_) -> ()' to expected argument type '(Int...) -> ()'


我什至将所有更改Int...Void...
我得到了相同的结果 但是
附加警告 When calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'? Replace '(Void...)' with '()',将 Void... 替换为 ()... 成功了


简化问题


let _: (()...) -> () = { _ in }

导致此错误:
Cannot convert value of type '(_) -> ()' to specified type '(()...) -> ()'
是否可以解决此问题?

标签: swiftparametersfunctional-programmingclosuresvariadic

解决方案


您需要在闭包中包含类型:

this { (foo: Int...) in }

类型推断引擎的功能还不足以解决这种情况。我怀疑它与SR-6030有关。


推荐阅读