Initializer helper methods


(Trevör Anne Denise) #1

It sometimes happen that some of the code used to initialize a type actually needs to be called again later in the object lifetime, it is tempting to move this code in a function in order to avoid code duplication, but variables initialization must be done directly in the body of init.
Has the possibility of integrating such functions already been discussed for Swift ?

Thank you


(Matthew Johnson) #2

I drafted a proposal for partial initializers in the early days of Swift evolution. I don't think it has come up since then.


(Trevör Anne Denise) #3

That would be a nice addition to the language!
About the proposed syntax, I don't like a lot the functionIdentifier.init(), not because of the inconsistency compared to calls outside of the initialiser as described by the proposal, but rather because this looks too similar to a method call such as foo.bar().
But indeed, it seems important to clearly indicate the role of the call to the partial initializer, how about using a prefix keyword :

init(x: Int) {
    ...
    partial foo(x: x)
    ...
}

I am not sure at all about the keyword, tough.