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
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.