GWRodriguez GWRodriguez - 5 months ago 13
Swift Question

1 struct, 3 Protocols, and 1 func to call them all

I am pretty sure this is only possible with classes, but wasn't sure if it's possible to do the following with structs:

protocol Pro {
var x: Int {get set}
mutating func foo()

protocol Pro2: Pro {
var y: Int {get set}

protocol Pro3: Pro {
var z: Int {get set}

extension Pro2 {
mutating func foo() {y *= 2}

extension Pro3 {
mutating func foo() {z += 2}

struct Aye: Pro2, Pro3 {
var x: Int = 0
var y: Int = 0
var z: Int = 0

mutating func foo() {
// call foo() from Pro2 and Pro3

I want the struct to call both the
calls from


Not currently, since

  • (as you probably already know) you need to implement Aye#foo with something since there are multiple default implementations with the same signature.
  • you cannot call within the implementation without causing infinite recursion, no matter how much casting you try.
  • the implementation in the struct will always be called instead of the default implement, so it is impossible to do any fancy casting at the call site.

I say "not currently" because I am not sure if this behavior is by design. As you said, this is no problem for classes.

(I had another answer, which was way off-base. Thanks @appzYourLife for correcting it.)