Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize Swift Class variables in declaration or with init?

Tags:

class

swift

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?

like image 464
Khanivore Avatar asked Sep 29 '22 08:09

Khanivore


1 Answers

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.

like image 126
Antonio Avatar answered Oct 16 '22 18:10

Antonio