“上下文关闭类型需要2个自变量"在Swift 4中使用reduce时出错
以下代码在Swift 3中编译
The following code compiles in Swift 3
extension Array where Element: Equatable {
var removeDuplicate: [Element] {
return reduce([]){ $0.0.contains($0.1) ? $0.0 : $0.0 + [$0.1] }
}
}
但是会产生错误
错误:上下文闭合类型'(_,_)-> _'需要2个参数,但闭合体中使用了1个
error: contextual closure type '(_, _) -> _' expects 2 arguments, but 1 was used in closure body
在Swift 4中.如何转换此代码以在Swift 4中进行编译?
in Swift 4. How to convert this code to be compiled in Swift 4?
传递给reduce
的闭包需要2个参数,例如$0
和$1
的缩写形式:
The closure passed to reduce
takes 2 parameters, e.g. $0
and $1
in the shorthand notation:
extension Array where Element: Equatable {
var removeDuplicate: [Element] {
return reduce([]) { $0.contains($1) ? $0 : $0 + [$1] }
}
}
(这将在Swift 3和Swift 4中进行编译.)
(This compiles in both Swift 3 and 4.)
在Swift 3中,您可以使用单个参数$0
,该参数将被推断为包含元素$0.0
和$0.1
的元组.
由于 SE-0110区分单元组和多参数函数类型.
In Swift 3 you could use single parameter $0
, which would the be inferred as a tuple with elements $0.0
and $0.1
.
This is not possible anymore in Swift 4, as a consequence of SE-0110 Distinguish between single-tuple and multiple-argument function types.
这是另一个演示更改的示例:这
Here is another example demonstrating the change: This
let clo1: (Int, Int) -> Int = { (x, y) in x + y }
let clo2: ((Int, Int)) -> Int = { z in z.0 + z.1 }
都可以在Swift 3和Swift 4中进行编译,但这是
both compiles in Swift 3 and 4, but this
let clo3: (Int, Int) -> Int = { z in z.0 + z.1 }
仅在Swift 3中编译,而不在Swift 4中编译.
compiles only in Swift 3, not in Swift 4.