Initializing Swift Variables

I have a question about initializing variables in swift.

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

Which one is the most correct?

class Class {

  var label: UILabel!

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

}

or

class Class {

  var label = UILabel()

  init() { … }

}
+4
source share
3 answers

In fact, you have 5 ways to initialize properties.

There is no right way, the way depends on needs.
Basically declare objects of type UILabelalways - if possible - as constants ( let).

5 ways:

  • Initialization in the ad line

    let label = UILabel(frame:...
    
  • Initializing in a method init, you do not need to declare the property as an implicit unwrapped optional.

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

.

  • , viewDidLoad, ( ) , var

    var label: UILabel!
    
    on viewDidLoad()
     ...
     label = UILabel(frame:...)
    }
    
  • (). , , .

    let label: UILabel = {
       let lbl = UILabel(frame:...)
       lbl.text = "Foo"
       return lbl
    }()
    
  • . ( ), , .
    var

    let labelText = "Bar"
    
    lazy var label: UILabel = {
       let lbl = UILabel(frame:...)
       lbl.text = "Foo" + self.labelText
       return lbl
    }()
    
+15

, init(). , target barButton , self .

class Foo {
    var barButton = UIBarButtonItem(title: "add", style: .Plain, target: self, action: #selector(self.someMethod))

    init(){
        //init here
    }
}

:

class Foo {
    var barButton : UIBarButton? 

    init(){
        barButton = UIBarButtonItem(title: "add", style: .Plain, target: self, action: #selector(self.someMethod))
    }
}

, , , . Apple

0
 var label: UILabel! 

, nil

var label = UILabel()

. . .

...

var: UILabel! var label = UILabel()?

0

Source: https://habr.com/ru/post/1660033/


All Articles