Swift Protocols with Associated Type Requirement and Default Implementation

倾然丶 夕夏残阳落幕 提交于 2019-12-04 14:11:21

The problem is unrelated to the type erasure and you'll get the same error message if you remove the struct AnyAnimal<Food> definition.

If you remove the feed() method from struct Cow then the compiler cannot infer the associated type Food. So either you use a concrete type in the default implementation:

extension Animal {
    func feed(food: Grass) -> Void {
        print("unknown")
    }
}

struct Cow: Animal {
}

or you define a type alias Food for each type using the default implementation:

extension Animal {
    func feed(food: Food) -> Void {
        print("unknown")
    }
}

struct Cow: Animal {
    typealias Food = Grass
}

It is also possible to define a default type for Food in the protocol:

protocol Animal {
    associatedtype Food = Grass
    func feed(food: Food) -> Void
}


extension Animal {
    func feed(food: Food) -> Void {
        print("unknown")
    }
}

struct Cow: Animal {
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!