扩展 FloatingPoint 集合
Extending Collection of FloatingPoint
我正在尝试扩展一组符合 FloatingPoint 标准的元素来计算平均值。
extension Collection where Element: FloatingPoint {
func sum() -> Element {
return reduce(0, +)
}
func average() -> Element {
return sum() / Int(count)
}
}
sum()
工作正常但 average()
有错误。
Binary operator '/' cannot be applied to operands of type
'Self.Element' and 'Int'
我不确定这是为什么。 Self.Element
是一个 FloatingPoint
。我希望能够划分这个。
(我也知道存在被零除的问题,但我稍后会解决。)
你的平均值没有工作,因为你试图用整数除以一些 FloatingPoint
类型。使用 Element(count)
创建相同类型的新元素进行划分。
extension Collection where Element: FloatingPoint {
func sum() -> Element {
return reduce(0, +)
}
func average() -> Element {
guard !isEmpty else { return 0 }
return sum() / Element(count)
}
}
这是可行的,因为 FloatingPoint
协议声明了以下初始化程序,
public init(_ value: Int)
这适用于 Swift 4.1,因为计数是 Int。对于 Swift 的早期版本,请使用
extension Collection where Element: FloatingPoint {
func sum() -> Element {
return reduce(0, +)
}
func average() -> Element {
guard !isEmpty else { return 0 }
return sum() / Element(Int(count))
}
}
我正在尝试扩展一组符合 FloatingPoint 标准的元素来计算平均值。
extension Collection where Element: FloatingPoint {
func sum() -> Element {
return reduce(0, +)
}
func average() -> Element {
return sum() / Int(count)
}
}
sum()
工作正常但 average()
有错误。
Binary operator '/' cannot be applied to operands of type 'Self.Element' and 'Int'
我不确定这是为什么。 Self.Element
是一个 FloatingPoint
。我希望能够划分这个。
(我也知道存在被零除的问题,但我稍后会解决。)
你的平均值没有工作,因为你试图用整数除以一些 FloatingPoint
类型。使用 Element(count)
创建相同类型的新元素进行划分。
extension Collection where Element: FloatingPoint {
func sum() -> Element {
return reduce(0, +)
}
func average() -> Element {
guard !isEmpty else { return 0 }
return sum() / Element(count)
}
}
这是可行的,因为 FloatingPoint
协议声明了以下初始化程序,
public init(_ value: Int)
这适用于 Swift 4.1,因为计数是 Int。对于 Swift 的早期版本,请使用
extension Collection where Element: FloatingPoint {
func sum() -> Element {
return reduce(0, +)
}
func average() -> Element {
guard !isEmpty else { return 0 }
return sum() / Element(Int(count))
}
}