0

code as below:

class Animall<T> {
    var value: T?
}

protocol Type {
    var name: String {get set}
}


class Duck: Type {
    var name = "duck"
}

var d = Animall<Duck>()
var duck = Duck()
duck.name = "duck"
d.value = duck

if let finalD = d as? Animall<Type> {
    print(finalD.value?.name)
}
else {
    print("Can't Convert")
}

It's Always log "Can't Convert". I want know the reason. I'm so puzzled. Duck is conform Type protocol. Why doesn't it convert!

kai
  • 310
  • 3
  • 14

1 Answers1

0

Animal<Duck> is not a "subclass" of Animal<Type> even if Duck conforms to the protocol Type. They are different classes, and this due to the fact that Swift generic types are invariant in respect to their generic argument. This means that every time you refer Animal with a different type, regardless the inheritance, the Animal "instances" are actually different, incompatible, types.

You can work around this "limitation" by moving the processing code to a generic function that operates on Type:

func doSomething<T: Type>(with animal: Animal<T>) {
    print(animal.value?.name)
}

doSomething(with: d)
Cristik
  • 30,989
  • 25
  • 91
  • 127