Inheritance - Equatable
Conforming Types - Numeric
public protocol AdditiveArithmetic : Equatable {
static var zero: Self { get }
static func + (lhs: Self, rhs: Self) -> Self
static func += (lhs: inout Self, rhs: Self)
static func - (lhs: Self, rhs: Self) -> Self
static func -= (lhs: inout Self, rhs: Self)
}
这个协议比较好理解, 遵守此协议则可以支持基础运算符。
看到一个很棒的例子。 协议配合条件筛选
extension Sequence where Element: AdditiveArithmetic {
func sum() -> Element {
return reduce(.zero, +)
}
}
let sum = [1, 2, 3, 4].sum()
print(sum)
10
精彩在于 Sequence 类型的数据(例: 数组), 内部都是支持 AdditiveArithmetic 类型的数据(例: int 、double),则可以调用此方法, 其他数组则不可以。
网友评论