“上下文关闭类型需要2个自变量"在Swift 4中使用reduce时出错 [英] "contextual closure type expects 2 arguments" error when using reduce in Swift 4

查看:256
本文介绍了“上下文关闭类型需要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.

这篇关于“上下文关闭类型需要2个自变量"在Swift 4中使用reduce时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆