我对 Double
有以下简单扩展,它在 Xcode 8 beta 3 之前的所有版本中都运行良好
public extension Double {
public func roundTo(_ decimalPlaces: Int) -> Double {
var v = self
var divisor = 1.0
if decimalPlaces > 0 {
for _ in 1 ... decimalPlaces {
v *= 10.0
divisor *= 0.1
}
}
return round(v) * divisor
}
}
从 Beta 4 开始,我在 return 中的 round
函数上收到“Cannot use mutating member on immutable value: 'self' is immutable” - 有人有任何线索吗?
最佳答案
这是由于与 the new rounding functions 的命名冲突造成的关于 FloatingPoint
协议(protocol),round()
和 rounded()
,已从 Xcode 8 beta 4 开始添加到 Swift 3。
因此,您需要通过指定您引用 Darwin
模块中的全局 round()
函数来消除歧义:
return Darwin.round(v) * divisor
或者,更好的是,只需使用新的舍入函数并在 v
上调用 rounded()
:
return v.rounded() * divisor
关于swift3 - Xcode 8 Beta 4 Swift 3 - "round"行为已更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39761838/