以下代码在
Swift 3中编译
extension Array where Element: Equatable { var removeDuplicate: [Element] { return reduce([]){ $0.0.contains($0.1) ? $0.0 : $0.0 + [$0.1] } } }
但会产生错误
error: contextual closure type ‘(_,_) -> _’ expects 2 arguments,but 1 was used in closure body
在Swift 4.如何转换此代码以在Swift 4中编译?
传递给reduce的闭包需要2个参数,例如$0和$1的简写符号:
extension Array where Element: Equatable { var removeDuplicate: [Element] { return reduce([]) { $0.contains($1) ? $0 : $0 + [$1] } } }
(这在Swift 3和4中都有编译)
在Swift 3中,您可以使用单个参数$0,这将被推断为元素$0.0和$0.1的元组.
由于SE-0110 Distinguish between single-tuple and multiple-argument function types,Swift 4中不再可能这样.
这是另一个证明变化的例子:这个
let clo1: (Int,Int) -> Int = { (x,y) in x + y } let clo2: ((Int,Int)) -> Int = { z in z.0 + z.1 }
两者都在Swift 3和4中编译,但是这个
let clo3: (Int,Int) -> Int = { z in z.0 + z.1 }
仅在Swift 3中编译,而不是在Swift 4中编译.