ilan bt ilan bt - 1 year ago 67
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


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?


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download