【问题标题】:"contextual closure type expects 2 arguments" error when using reduce in Swift 4在 Swift 4 中使用 reduce 时出现“上下文闭包类型需要 2 个参数”错误
【发布时间】:2018-03-08 00:07:54
【问题描述】:

以下代码在 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 个

在 Swift 4 中。如何将此代码转换为在 Swift 4 中编译?

【问题讨论】:

  • 原始错误消息是由于代码中的虚假(0)。但即使没有这个错误,Swift 3 到 4 的转换问题仍然存在。我冒昧地编辑了您的问题,以使其(希望)对未来的读者更有用。 – 请检查您是否可以。
  • 顺便说一句:我注意到你得到了所有问题的答案,但到目前为止从未接受答案。如果您不知道:接受答案很重要,因为它既奖励海报以解决您的问题,又通知其他人您的问题已解决。请参阅What should I do when someone answers my question?How does accepting an answer work? 了解更多信息。

标签: arrays swift reduce swift4 equatable


【解决方案1】:

传递给reduce 的闭包有两个参数,例如$0$1 的简写:

extension Array where Element: Equatable {
    var removeDuplicate: [Element] {
        return reduce([]) { $0.contains($1) ? $0 : $0 + [$1] }
    }
}

(这在 Swift 3 和 4 中都可以编译。)

在 Swift 3 中,您可以使用 single 参数 $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 中不编译。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    相关资源
    最近更新 更多