Swift Generics & Upcasting

后端 未结 1 799
野性不改
野性不改 2020-12-03 09:09

I\'ve got a quick question regarding generics in Swift. The problem is I\'m trying to store a variable that takes a generic as a parameter, but am unable to cast it up to th

1条回答
  •  独厮守ぢ
    2020-12-03 09:36

    Swift generics are not covariant. That is to say, exactly what the error says: you can't automatically say a Basket is a kind of Basket even if Apple is a kind of Fruit. There is good reason for this.

    Consider the following code:

    class Fruit {}
    class Apple: Fruit {}
    class Orange: Fruit {}
    
    class Basket {
        private var items: [T]
        func add(item: T) {
            items.append(item)
        }
        init() {}
    }
    
    func addItem(var basket: Basket, item: T) {
        basket.add(item)
    }
    
    let basket:Basket = Basket()
    
    addItem(basket as Basket, Orange())
    

    This would be legal code if Basket were considered a Basket, and I'd be allowed to add an orange to a basket of apples.

    0 讨论(0)
提交回复
热议问题