在Swift 2.0中使用reduce()时出现错误

7

注意:这也适用于Swift 3.0

当我尝试使用reduce函数时,会出现以下错误:

reduce不可用:在序列上调用'reduce()'方法

我已经知道如何使用enumerate()函数解决此问题,但似乎无法解决这个问题。以下是返回错误的代码行:

var hashValue: Int {
    return reduce(blocks, 0) { $0.hashValue ^ $1.hashValue }
}
1个回答

14

你可以像解决关于enumerate()的问题一样来修复这个。在Swift 2中,reduce已经不再作为一个全局函数存在了,而是通过协议扩展添加到所有符合SequenceType协议的对象中作为实例方法。使用方法如下所示。

var hashValue: Int {
    return blocks.reduce(0) { $0.hashValue ^ $1.hashValue }
}

非常感谢!我不确定是因为reduce()中有两个值。 - Gary Simcox

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接