This does not compile (however Double does conform to BinaryFloatingPoint):
extension Array where Element == any BinaryFloatingPoint {
var mean: Double? {
if isEmpty { return nil }
return reduce(0.0) { ret, x in ret + Double(x) } / Double(count)
}
}
let d = [2.3, 4.5]
print(d.mean!) // No exact matches in reference to property 'mean'
To compile, I must do this:
let d: [any BinaryFloatingPoint] = [2.3, 4.5]
I’m having some difficulty understanding why this is. When an attempt to DRY requires that you add type statements at call sites, it feels like the purpose is defeated. Is there a way to improve this implementation?
>Solution :
You can’t use a specific type when you say the computed property in the extension can be used for a protocol. So make use of the generic type Element and the protocol
extension Array where Element: BinaryFloatingPoint {
var mean: Element? {
if isEmpty { return nil }
return reduce(.zero) { ret, x in ret + x } / Element(count)
}
}
And you could extend it to be an extension to Collection instead