Member-wise initialiser with nil members


(Mohammed M. Ennabah) #1

Swift structs supports member-wise initialiser, for instance:

struct User {
  let id: String
  let name: String
  var books: [Book]?
}

The User structure automatically receives the following initialiser

User.init(id: String, name: String, books: [Book]?)

Now, if we changed User to:

struct User {
  let id: String
  let name: String
  var books: [Book]? = nil
}

It generates the same initialiser as before:

User.init(id: String, name: String, books: [Book]?)

Since the member books has = nil, why it doesn't generate the following too?:

User.init(id: String, name: String)

(Jordan Rose) #2

If you have two properties with initial values, you'd have to generate 4 initializers; three, 8; and so on. The feature we suspect would be more useful is to use the initial values as default arguments, which is captured in SR-5534. Of course, this would need to go through the Swift Evolution Process, since it's a language change.


#3

It is worth considering though that for this specific example,
var books: [Book]?
and
var books: [Book]? = nil
actually mean the same thing since optionals default to nil anyways.

I believe that that's actually an important inconsistency that would be introduced and therefore would need to be considered in the evolution progress.


(Mohammed M. Ennabah) #4

Indeed it does, but if you would write the initialiser yourself, it would make difference since Swift will synthesise another initialiser just because the = nil.