Sanjeet Suhag Sanjeet Suhag - 5 months ago 11
Swift Question

Is using nested initializers in Swift bad practice?

Say I have a Swift

struct
setup like this :

struct User {
// Properties
var name: String?
var username: String!
var email: String?
}


Now, the way I look at it, there are 2 ways of designing the initializer.

Here's the first:

init(username: String) {
self.username = username
}

init(username: String, name: String) {
self.username = username
self.name = name
}

init(username: String, name: String, email: String) {
self.username = username
self.name = name
self.email = email
}


Here's the second :

init(username: String) {
self.username = username
}

init(username: String, name: String) {
self.init(username: username)
self.name = name
}

init(username: String, name: String, email: String) {
self.init(username: username, name: name)
self.email = email
}


Which is the better practice and does it even make a difference ?

Answer

Actually you need only one initializer at all.

username seems to be required, so declare it as non-optional.

If you provide a default value for the other parameters they could be omitted.

struct User {
  // Properties
  var name: String?
  var username : String
  var email: String?

  init(username: String, name: String? = nil, email: String? = nil) {
    self.username = username
    self.name = name
    self.email = email
  }
}

Now you can use these three forms with one initializer

User(username: "Foo")
User(username: "Foo", name: "Bar")
User(username: "Foo", name: "Bar", email:"john@doe.com")