Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Variables Initialization

I have a question about variables initialization in swift.

I have two ways to initialize a variable (as "property" of a class in Objective-C).

Which of them is the most correct?

class Class {

  var label: UILabel!

  init() { ... label = UILabel() ... }

}

or

class Class {

  var label = UILabel()

  init() { … }

}
like image 619
Alexander Kuzyaev Avatar asked Nov 07 '16 07:11

Alexander Kuzyaev


People also ask

What does init () do in Swift?

Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.

How do you initialize a structure in Swift?

In Swift, all structs come with a default initializer. This is called the memberwise initializer. A memberwise initializer assigns each property in the structure to self. This means you do not need to write an implementation for an initializer in your structure.


1 Answers

Actually you have 5 ways to initialize properties.

There is no correct way, the way depends on the needs.
Basically declare objects like UILabel always – if possible – as constant (let).

The 5 ways are:

  • Initialization in the declaration line

    let label = UILabel(frame:...
    
  • Initialization in the init method, you don't have to declare the property as implicit unwrapped optional.

    let label: UILabel
    init() { ... label = UILabel(frame:...) ... }
    

The first two ways are practically identical.

  • Initialization in a method like viewDidLoad, in this case you have to declare the property as (implicit unwrapped) optional and also as var

    var label: UILabel!
    
    on viewDidLoad()
     ...
     label = UILabel(frame:...)
    }
    
  • Initialization using a closure to assign a default (computed) value. The closure is called once when the class is initialized and it is not possible to use other properties of the class in the closure.

    let label: UILabel = {
       let lbl = UILabel(frame:...)
       lbl.text = "Foo"
       return lbl
    }()
    
  • Lazy initialization using a closure. The closure is called (once) when the property is accessed the first time and you can use other properties of the class.
    The property must be declared as var

    let labelText = "Bar"
    
    lazy var label: UILabel = {
       let lbl = UILabel(frame:...)
       lbl.text = "Foo" + self.labelText
       return lbl
    }()
    
like image 69
vadian Avatar answered Sep 21 '22 13:09

vadian