0

Is something like this possible in Swift?

protocol SpeaksGerman {
    func speakGerman()
}

protocol SpeaksFrench {
    func speakFrench()
}

protocol HasGermanSpeaker {
    var speaker: SpeaksGerman! {get}
}

protocol HasFrenchSpeaker {
    var speaker: SpeaksFrench! {get}
}

class IHaveAPolyglotSpeaker: HasGermanSpeaker {
    var speaker: (SpeaksGerman & SpeaksFrench)!
}

Since var speaker is declared as conforming to both SpeaksGerman and SpeaksFrench I'd expect IHaveAPolyglotSpeaker to conform to any of the HasGermanSpeaker or HasFrenchSpeaker protocols.

marosoaie
  • 2,352
  • 23
  • 32
  • _I'd expect IHaveAPolyglotSpeaker to conform to any of the HasGermanSpeaker or HasFrenchSpeaker protocols._ Absolutely it would not. `HasGermanSpeaker` is not inherited by `SpeaksGerman` so there is no way to know `IHaveAPolyglotSpeaker.speaker` would conform to `HasGermanSpeaker` or `HasFrenchSpeaker`. You need to rethink your design. – Ozgur Vatansever Nov 06 '17 at 16:08
  • hmm, `HasGermanSpeaker` requires a property `speaker` of type `SpeaksGerman`. `IHaveAPolyglotSpeaker` has a a property `speaker` of type `SpeaksGerman`. I'm not sure what inheritance has to do with it. – marosoaie Nov 06 '17 at 16:10
  • Doesn't matter. You still don't know if `IHaveAPolyglotSpeaker.speaker` conforms to `HasGermanSpeaker`. – Ozgur Vatansever Nov 06 '17 at 16:11
  • @OzgurVatansever `IHaveAPolyglotSpeaker.speaker` conforms to `SpeaksGerman`, it doesn't have to conform to `HasGermanSpeaker` – marosoaie Nov 06 '17 at 16:12
  • but not to `HasGermanSpeaker` which is what you want it to. Your design is definitely flawed. Maybe you should explain us what you really want to achieve. – Ozgur Vatansever Nov 06 '17 at 16:13
  • 1
    Compare https://stackoverflow.com/q/42561685/2976878 – in short, there's no real reason why this isn't possible; it just isn't supported yet. – Hamish Nov 06 '17 at 16:13
  • @Hamish hmm, it looks similar example but I'm not sure I get it entirely – marosoaie Nov 06 '17 at 16:28
  • @OzgurVatansever `IHaveAPolyglotSpeaker` has a `speaker` var with the type `SpeaksGerman`, which is exactly what conforming to `HasGermanSpeaker` means. I think you're confusing the protocol that `speaker` conforms to with the one `IHaveAPolyglotSpeaker` needs to conform to. – marosoaie Nov 06 '17 at 16:31
  • Make your func speakGerman() and your func speakFrench() optional by putting the keywork optional in front of them and I think it will work. – Arrabidas92 Nov 06 '17 at 18:28
  • @marosoaie What part exactly are you unsure about? I've closed this as a dupe for now, but am happy to re-open if you could clarify what part you're unsure about. – Hamish Nov 07 '17 at 00:29

0 Answers0