数组 – 在Swift 4中使用reduce时,“上下文闭包类型需要2个参数
发布时间:2020-12-14 02:25:47 所属栏目:百科 来源:网络整理
导读:以下代码在 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 arg
以下代码在
Swift 3中编译
extension Array where Element: Equatable { var removeDuplicate: [Element] { return reduce([]){ $0.0.contains($0.1) ? $0.0 : $0.0 + [$0.1] } } } 但会产生错误
在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的元组. 这是另一个证明变化的例子:这个 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中编译. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容