Tom van Zummeren
Tom van Zummeren

Reputation: 9220

Use of generics supertype in arrays

I have a question concerning generics in Swift. Why isn't this possible?

class GenerifiedClass<T> {
    func doSomething(thing: T) {
        print("doing something with \(thing)")
    }
}

class SuperType {}
class TypeA: SuperType {}
class TypeB: SuperType {}
class TypeC: SuperType {}

let a = GenerifiedClass<TypeA>()
let b = GenerifiedClass<TypeB>()
let c = GenerifiedClass<TypeC>()

let array: [GenerifiedClass<SuperType>] = [a, b, c]   // compile error

To clarify my question: why can't I type my array as [GenerifiedClass<SuperType>]? I kind of know why, because in Java for example this would also not be possible. But at least in Java there is syntax to solve this:

List<? extends SuperType> list = new ArrayList<>()

Is there an equivalent in Swift to <? extends SuperType> in Java?

Upvotes: 2

Views: 319

Answers (1)

Cristik
Cristik

Reputation: 32786

This is related to covariance of generics in Swift. Basically GenerifiedClass<SuperType> is not a superclass of GenerifiedClass<TypeA>, but is merely a sibling class, and this is why you cannot use it where you'd use polymorphism.

To answer the extends question, yes this is possible also in Swift:

class SuperType {}
class TypeA: SuperType {}
class TypeB: SuperType {}
class TypeC: SuperType {}

let a = TypeA()
let b = TypeB()
let c = TypeC()

let array: Array<SuperType> = [a, b, c]

,or

let array: [SuperType] = [a, b, c]

Upvotes: 3

Related Questions