更新到 Swift 3 后奇怪的转义函数行为 [英] Weird escaping function behavior after updating to Swift 3
问题描述
更新到 Swift 3 后,我在使用以下代码行时遇到困难:
I'm having difficulties with the following lines of code after updating to Swift 3:
private var functionHandlers = [(() -> Int) -> ()]()
private var myFunction: (() -> Int)?
func doRegister() {
functionHandlers.append { (f: (() -> Int)) in
myFunction = f
}
}
这给了我编译器错误:Assigning non-escaping parameter 'f' to an escapingclosure
然后,我尝试了这个:
func doRegister() {
functionHandlers.append { (f: @escaping (() -> Int)) in
myFunction = f
}
}
还有这个:
func doRegister() {
functionHandlers.append { (f: (@escaping () -> Int)) in
myFunction = f
}
}
在这两种情况下,都修复了我的第一个错误,但随后又给了我一个新的编译器错误:Cannot convert value of type '(@escaping (() -> Int)) ->()' 到预期的参数类型 '(() -> Int) ->()'
which, in both cases, fixed my first error, but then gave me a new compiler error: Cannot convert value of type '(@escaping (() -> Int)) -> ()' to expected argument type '(() -> Int) -> ()'
然后我尝试改变 functionHandlers
的类型如下:
So then I tried changing the type of functionHandlers
as follows:
private var functionHandlers = [(@escaping (() -> Int)) -> ()]()
但这只会导致语法错误.
but that just resulted in a syntax error.
谁能向我解释为什么会发生这种情况以及我可以做些什么来解决这个问题?
Can anyone explain to me why this is happening and what I can do to fix this?
推荐答案
在我看来像是一个错误.出于某种原因,编译器不喜欢这种语法:
Looks like a bug to me. For some reason, the compiler doesn't like the syntax:
private var functionHandlers = [(@escaping () -> Int) -> ()]()
但它确实喜欢:
private var functionHandlers : [(@escaping () -> Int) -> ()] = []
这是相同的症状,但我不确定它是否与 编译器拒绝带有嵌套类型的 [TypeA.TypeB]()
语法.虽然和那个问题一样,但另一种解决方法是使用 typealias
:
It's the same symptom, but I'm unsure it's the same cause as the compiler rejecting the [TypeA.TypeB]()
syntax with nested types. Although like that problem, another way of solving it is by using a typealias
:
typealias F = (@escaping () -> Int) -> ()
private var functionHandlers = [F]()
然后您可以实现 doRegister()
,因为您尝试将其正确实现为:
You can then implement doRegister()
as you correctly tried to implement it as:
func doRegister() {
functionHandlers.append { (f: @escaping () -> Int) in
myFunction = f
}
}
尽管您当然应该提交错误报告超过[(@escaping () ->整数) ->()]()
未编译.
Although you should certainly file a bug report over [(@escaping () -> Int) -> ()]()
not compiling.
这篇关于更新到 Swift 3 后奇怪的转义函数行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!