这是我目前得到的。它至少有这些问题:
Measurement<UnitType>
数组上使用时崩溃
单位是混合的,例如克和毫克。zero
属性不如静态替代方法那样,对于空序列,它允许返回类型为类型zero
,而不是nil
。我无法弄清楚这是否可以避免。
我使用第一个扩展名,因为当前版本的Swift中不存在Sequence.first
。
import Foundation
public extension Sequence {
var first: Iterator.Element? {
return self.first{_ in true}
}
}
public extension Sequence where Iterator.Element: SummableUsingInstanceZero {
var sum: Iterator.Element? {
guard let zero = first?.zero
else {return nil}
return self.reduce(zero, +)
}
}
public protocol SummableUsingInstanceZero {
static func + (_: Self, _: Self) -> Self
var zero: Self {get}
}
extension Measurement: SummableUsingInstanceZero {
public var zero: Measurement {
return Measurement(
value: 0,
unit: unit
)
}
}
答案 0 :(得分:0)
这个问题很旧,但是解决方案仍然不是内置的。遵循AdditiveArithmetic
是必经之路!
import Foundation
extension Measurement: AdditiveArithmetic where UnitType: Dimension {
public static var zero: Self {
Self( value: 0, unit: .baseUnit() )
}
public static func += (measurement0: inout Self, measurement1: Self) {
measurement0 = measurement0 + measurement1
}
public static func -= (measurement0: inout Self, measurement1: Self) {
measurement0 = measurement0 - measurement1
}
}