4 ms·
Well, I think the semantics of your class hierarchy are not what you expect. You're saying FruitHolder can hold any kind of Fruit but then you're trying to "tak
by leftspin 11y ago
Well, I think the semantics of your class hierarchy are not what you expect. You're saying FruitHolder can hold any kind of Fruit but then you're trying to "take back" that definition in PeachBasket where you're saying "just kidding, it only holds one kind of Fruit".
It's better if you explicitly start with the definition that a FruitHolder can only store a type of Fruit, but then use inheritance to abstract your fruits.
This works fine:
class Fruit {}
class Peach: Fruit {}
protocol FruitHolder
{
typealias FruitKind
var fruits: [FruitKind] { get }
}
class PeachBasket: FruitHolder
{
typealias FruitKind = Peach
var fruits: [FruitKind] = []
}
class FruitBasket: FruitHolder
{
typealias FruitKind = Fruit
var fruits: [FruitKind] = []
}
var fruitBasket = FruitBasket()
fruitBasket.fruits += [Fruit(), Peach()]
var peachBasket = PeachBasket()
// ERROR:
peachBasket.fruits += [Fruit(), Peach()]