1

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.

Vince O'Sullivan
  • 2,611
  • 32
  • 45

2 Answers2

1

The problem with this code

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

is that you declared data as a generic type that must be Comparable. It means it could contains any value of type T. And T is defined when the class is used.

Foo<String>()
Foo<Double>()
Foo<Bool>()

Look at the example above. In the first case T is a String. With this information it should be clear that this line cannot compile

let data: [T]  = [Double]()

because it would be equivalent to writing

let data: [String]  = [Double]()

that is obviously wrong.

Solution

As already suggested by @Eric D.

class Foo<T: Comparable> {
    let data: [T]  = []
}

Now data is populated with an empty array of the correct type.

Examples

So in this case

Foo<String>()

it is an array of String.

In this case

Foo<Double>()

it is populated with an array of Double.

And finally in this case

Foo<Bool>()

with an array of Bool.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
0

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.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • Got it. The conformance happens at run-time, not compile-time. – Vince O'Sullivan Jul 12 '16 at 13:39
  • @VinceO'Sullivan The conformance is known at compile-time, but with the code you posted in your question, [T] is not the same as [Comparable] because T is equal to whatever comparable type was passed into the generic parameter, as explained by appzYourLife in an answer below. So if Int was passed in, then you would be trying to create a variable with type [T] (which is [Int]), and then initialize it with an array of Doubles. – Matthew Seaman Jul 12 '16 at 20:54