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?
}
With Swift 5.7 there is now a concept of a "primary" associatedtype
which allows you to do this:
protocol Animal<Item> {
associatedtype Item
func doSomething(with item: Item)
}
You then set it as a property like this:
class Owner<Item> {
var item: Item
var animal: any Animal<Item>
}
See https://www.donnywals.com/what-are-primary-associated-types-in-swift-5-7/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.