Khanivore
Khanivore

Reputation: 207

initialize Swift Class variables in declaration or with init?

In Swift you can initialize a variable in a class when you declare the variable:

var name: String = "John"

or you can initialize with init:

var name: String

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

Which version do you use and when?

Upvotes: 5

Views: 4909

Answers (1)

Antonio
Antonio

Reputation: 72790

Unless you are providing the initial value as an initializer parameter, for which you have for obvious reasons do that in the initializer, you can use any of the 2 ways.

My rules are:

  • if there are several initializers, and the property is initialized with the same value in all cases, I prefer inline initialization
  • if the property is (or should be) immutable, I prefer inline initialization
  • if the property can change during the instance lifetime, I prefer constructor initialization

but besides the first one, the other 2 are just based on personal preference.

Upvotes: 4

Related Questions