Search code examples
swiftprotocols

Swift Protocol Extension - Can't Access Func


If I have a series of protocols like so:

    protocol Customer {

    var name:String { get set }
    var age: Int { get set }
    var startDate:Date { get set }
    var meals:Array<String> { get set }
    var market:Int { get set }

}

protocol Vegan:Customer {

}

protocol Vegetarian:Customer {

}

protocol Paleo:Customer {


}

and extension like so:

    extension Customer where Self:Vegan, Self:Vegetarian {

    func getMeals() -> Array<String> {
        return ["VeganMeal1", "VeganMeal2", "VeganMeal3", "VeganMeal4"]
    }
}

extension Customer where Self:Vegetarian {

    func getMeals() -> Array<String> {
        return ["VegetarianMeal1", "VegetarianMeal2", "VegetarianMeal3", "VegetarianMeal4"]
    }
}

extension Customer where Self:Paleo {

    func getMeals() -> Array<String> {
        return ["PaleoMeal1", "PaleoMeal2", "PaleoMeal3", "PaleoMeal4"]
    }
}

and this struct

    struct aCustomer:Customer, Vegan {

    var name:String
    var age: Int
    var startDate:Date
    var meals:Array<String>
    var market:Int

}

when I create a new object based on that struct

var newCustomer = aCustomer(name:"William", age:40, startDate:Date(), meals:[], market:1)

how come I can't access the getMeals function in the extensions? I get an error stating getMeals is an ambiguous reference.

enter image description here


Solution

  • extension Customer where Self:Vegan, Self:Vegetarian {
    

    extends Customer in the case where the adopter or Customer also both adopts Vegan and Vegetarian. Your aCustomer (a struct type starting with a small letter?? the horror, the horror) does not do that, so the extension doesn't apply to it.

    If the goal is to inject the same code either when the adopter adopts Vegan or when the adopter adopts Vegetarian, use two extensions, or, if you don't like the repetition, have them both adopt some "higher" protocol that is extended with the desired code to be injected.