Reputation: 1414
I'm trying to extend a Collection of FloatingPoint-conforming elements to work out an average.
extension Collection where Element: FloatingPoint {
func sum() -> Element {
return reduce(0, +)
}
func average() -> Element {
return sum() / Int(count)
}
}
sum()
works fine but average()
has an error.
Binary operator '/' cannot be applied to operands of type 'Self.Element' and 'Int'
I'm not sure why this is. Self.Element
is a FloatingPoint
. I would expect to be able to divide this.
(I'm also aware that there's a divide-by-zero issue, but I'll fix that later.)
Upvotes: 0
Views: 64
Reputation: 21154
You average didnt work because you were trying to divide some FloatingPoint
type with integer. Use Element(count)
to create new element of same type to divide.
extension Collection where Element: FloatingPoint {
func sum() -> Element {
return reduce(0, +)
}
func average() -> Element {
guard !isEmpty else { return 0 }
return sum() / Element(count)
}
}
And this works because FloatingPoint
protocol declares following initializer,
public init(_ value: Int)
This works with Swift 4.1, since count is Int. For earlier versions of Swift use,
extension Collection where Element: FloatingPoint {
func sum() -> Element {
return reduce(0, +)
}
func average() -> Element {
guard !isEmpty else { return 0 }
return sum() / Element(Int(count))
}
}
Upvotes: 3