Is it possible to use protocol with associated type as a property to match some constraints?
Here is an example which I'm struggling with:
protocol Animal {
associatedtype Item
func doSomething(with item: Item)
}
class Owner<Item> {
var item: Item
// I have to be sure that Animal.Item == Item
var animal: Animal
}
Protocols with associated types cannot be used as the type of a property. Instead of constraining animal
's type, you can try constraining the generic type of Owner
:
class Owner<AnimalType> where AnimalType : Animal {
var item: AnimalType.Item?
var animal: AnimalType?
}
You don't need Item
because you can just use AnimalType.Item
for this. That's just how associated types work. Say you want a function that accepts an Item
, you can just use AnimalType.Item
in place of that:
func someFunc(someParameter: AnimalType.Item) { ... }
Or maybe this might fit your needs?
class Owner<AnimalType, ItemType> where AnimalType : Animal, AnimalType.Item == ItemType {
var item: ItemType?
var animal: AnimalType?
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With