melaka
melaka

Reputation: 719

swift - Generic classes with inheritance

When I try to execute the code below, I get the following error

error: cannot convert value of type 'X' to specified type 'X'

Doesn't swift support inheritance with generics? Is there a workaround for this?

class Parent{ }

class Child:Parent{ }

class X<T>{
    var name: String?
}

var test:X<Parent> = X<Child>() //Compiler Error

Upvotes: 3

Views: 905

Answers (1)

Andreas Oetjen
Andreas Oetjen

Reputation: 10209

In Swift, generics are invariant, e.g. any X<A> will never be assignable to X<B>, regardless of the inheritence relationship between A and B.

Nevertheless, there are some exceptions to this rule, regarding Arrays and Optionals (and mabye some other types):

var array2:[Parent] = [Child]()
// same as:
var array1:Array<Parent> = Array<Child>()

var opt1:Parent? = Child()
// same as:
var opt2:Optional<Parent> = Optional<Child>(Child())

These will compile (since Swift 3) - but these a special cases treated by some hard-coded rules of the the compiler.

Upvotes: 3

Related Questions