3

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
5
  • 1
    What is your end goal here? It is hard to come up with alternatives if it’s not clear what you are trying to achieve. Commented Jun 12, 2018 at 10:24
  • Hi @DamiaanDufaux, exact context is a bit complex. But in short, I'm having a method which should be able to return either X<Parent> or X<Child> Commented Jun 12, 2018 at 11:14
  • Can't you use a protocol for your method? Create a new protocol P, make class X<T> conform to P. Then use P as return type for your method. You can then return X<Child> as well as X<Parent> from within your method. Commented Jun 12, 2018 at 13:10
  • I have no control over the class X. It's defined in a library Commented Jun 13, 2018 at 2:44
  • You can conform it via an extension extension X: P {…} Commented Jun 13, 2018 at 7:17

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Is there any workaround to this? Maybe defining things differently?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.