swift3xcode8-beta2

Are Doubles Comparable in Swift


Swift 3, Xcode 8β2.
I've implemented a class that sorts Comparable data and attempted to test it using Doubles. Unfortunately, I'm getting the error "Cannot convert value of type '[Double]' to specified type '[T]'.". I've reproduced the error in the sample code below:

class foo<T: Comparable> {
    let data: [T]  = [Double]()
}

Am I right is assuming that Doubles are Comparable and, if so, how do I eliminate the error above?
Thx.


Solution

  • Your property has a generic type, T: it can't be declared as holding a concrete type. Just use [T] in the declaration, and use Double when instantiating the class.

    For my example I've also made the property a var so that I could modify it:

    class Foo<T: Comparable> {
        var data: [T] = [T]()
    }
    
    let f = Foo<Double>()
    f.data = [42.0, 33.0]
    f.data.sort()
    print(f.data)
    

    Gives

    [33.0, 42.0]

    as expected.