第一次关闭有效。但是,一旦我取出虚拟分配,闭包就会停止工作(addUpClosureRedFlagged)。有人知道为什么吗?
let addUpClosureWorking: (Int ...) -> Int = {
let dummy = "Anything" // Comment out and wait for the error...
return $0.reduce(0, combine: +)
}
let addUpClosureRedFlagged: (Int ...) -> Int = {
return $0.reduce(0, combine: +) // Should work, but doesn't!
}
addUpClosureWorking(1, 2, 3, 4, 5) // 15
从当前的 Swift (2.1) 开始,当仅包含一行时,闭包的类型推断可能会表现得有点奇怪,请参见例如这个有点相关的问题 https://stackoverflow.com/questions/35184847/inline-if-statement-mutating-inout-parameter-in-a-void-return-closure-weird-err;期望在闭包中显式包含函数类型签名。
这个(编译器)“bug”/闭包限制(至少)对于可变参数以及inout
论点:
// variadiac argument example
let fooErr1: (Int ...) -> Int = {
return $0.reduce(0, combine: +)
}
// or: let fooErr1: (Int ...) -> Int = { $0.reduce(0, combine: +) }
/* error: cannot convert value of type '(_) -> Int'
to specified type '(Int...) -> Int' */
// inout argument example
let fooErr2: (inout _: Int) -> Int = {
return $0
}
// or: let fooErr2: (inout _: Int) -> Int = { $0 }
/* error: cannot convert value of type '_ -> Int'
to specified type '(inout Int) -> Int' */
这可以通过在闭包中显式包含 function:s 类型签名来避免,或者包含anyreturn 语句之前的语句(因此扩展了闭包以包含多行)。
/* Avoiding fooErr1:
- explicitly state function type signature in closure */
let foo: (Int ...) -> Int = {
(bar: Int ...) -> Int in
return bar.reduce(0, combine: +)
}
/* - include any kind of statment prior to return statement */
let foo2: (Int ...) -> Int = {
(); return $0.reduce(0, combine: +)
}
/* Avoiding fooErr2:
- explicitly state function type signature in closure */
let foo3: (inout _: Int) -> Int = {
(inout bar: Int) -> Int in
return bar
}
/* - include any kind of statment prior to return statement */
let foo4: (inout _: Int) -> Int = {
(); return $0
}
为什么?我在上面写了“bug”,但也许更多的是编译器对闭包类型推断的当前限制;正如 Pradeep K 在他的回答中所写,这很可能是由于 Swift 编译器的一些复杂性造成的,在这些情况下类型推断失败。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)