function - 在 Swift 2.0 中使用 reduce() 时出错

标签 function swift reduce swift2

注意:这也适用于 Swift 3.0

当我尝试使用 reduce 函数时,我收到一条错误消息:

reduce is unavailable: call the 'reduce()' method on the sequence

我已经想出了如何使用 enumerate() 函数来实现这一点,但我似乎无法解决这个问题。这是返回错误的代码行:

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

最佳答案

解决这个问题的方式与使用 enumerate() 解决问题的方式相同。在 Swift 2 中,reduce 作为全局函数被移除,并通过协议(protocol)扩展添加为所有符合 SequenceType 协议(protocol)的对象的实例方法。用法如下。

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

关于function - 在 Swift 2.0 中使用 reduce() 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30825671/

相关文章:

ios - 在 UIPageViewController (Swift) 中可靠地跟踪页面索引

swift - 有没有办法在 Swift 中为 (`==` 自动定义 compare `struct` ) 函数?

swift - 从 Reduce 获取任意类型

javascript - 在 JavaScript 中,构造函数和作为构造函数调用的函数返回对象之间有什么区别?

javascript - js创建高级原型(prototype)

function - 如何理解这个递归结果

php - 无法回显函数中获取的变量

ios - 点击 GMSPolygon Swift

javascript - 使用reduce javascript将字符串转换为对象