ilan bt ilan bt - 1 month ago 6
Swift Question

Generics with inheritance error

I have an 2 objects inheriting from the same further.
And a Generic object Of the furthers type.
I want to save a list of generic object but i get an error.


//Error: Cannot convert value of Type Node to expected argument type Node


Code:

class Pet {

}

class Cat: Pet {

}

class Dog: Pet {

}


public class Node<T> {
public var value: T

public init(value: T) {
self.value = value
}
}

var list = [Node<Pet>]()

//Error: Cannot convert value of Type Node<Dog> to expected argument type Node<Pet>
list.append(Node<Dog>(value: Dog()))


Why is this happening? any suggestions?




EDIT:

If Dog is of Kind Pet why cant i create a list of Node
And add to it a Node?

Answer

Swift is strict about types. You can't append Node<Dog> when Node<Pet> is expected.


Cast to necessary type by yourself Dog() as Pet:

list.append(Node<Pet>(value: Dog() as Pet))

Later if you need to access the object and get the correct type, you have to downcast:

if let myDog = list[0].value as? Dog {
  print("woff woff")
}

See the working demo.

Read more details about types casting.