Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is explicitly typing the array as BinaryFloatingPoint necessary?

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading