Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protocol with associated type as property

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
}
like image 729
Nominalista Avatar asked May 06 '18 09:05

Nominalista


1 Answers

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?
}
like image 112
Sweeper Avatar answered Nov 15 '22 11:11

Sweeper