Is it possible to add struct initializer via protocol extension?

The title pretty much says it all. I need to add an initializer to struct, via protocol extension. Can this be done?

Answered by ahltorp in 18400022

An initializer has to be a designated initializer or a convenience initializer. An convenience initializer is "not allowed in non-class type[s]". A designated initializer has to "[initialize] all stored properties", which it cannot do, since the protocol extension would have to know the list of properties in the struct, and it cannot know that.


So I guess the answer is no.

Accepted Answer

An initializer has to be a designated initializer or a convenience initializer. An convenience initializer is "not allowed in non-class type[s]". A designated initializer has to "[initialize] all stored properties", which it cannot do, since the protocol extension would have to know the list of properties in the struct, and it cannot know that.


So I guess the answer is no.

This seems like the correct answer. This would, however, be a very nice feature to have. It might even be doable with some limits:


  • If you add an initializer into protocol extension, the protocol must declare properties that correspond to all stored properties of the type you are extending.
  • The initializer must set all properties of the protocol


So, for example, if you are extending this struct:


struct Test {
     var a: Int
     var b: String
}

Then you'll have to declare the protocol like this:


protocol Proto {
     var a: Int { get set }
     var b: String { get set }
     init()
}

And in your protocol extension:


extension Test: Proto {
     init() {
          self.a = 0
          self.b = ""
     }
}
Is it possible to add struct initializer via protocol extension?
 
 
Q