1

Take an example

Class A {

var a : Int

 override func viewDidLoad() {
    super.viewDidLoad()
        a=0
}

when it says variable is not initialized, even when i already declared in class first.

Sahil
  • 9,096
  • 3
  • 25
  • 29
Rushi trivedi
  • 737
  • 1
  • 15
  • 37

3 Answers3

2

viewDidLoad is not the equivalent of init

I suggest you either use optionals:

var a:Int?

or you can initialize your variable directly in its declaration

var a:Int = 0

Last but not least, if you want to initialize any other way, do it in the init

override init() {
    super.init()

    a = 0
}
The Tom
  • 2,790
  • 6
  • 29
  • 33
1

when you declare property in the class with Int it indicates it has no initializers. either give value at initialize time var a : Int = 0 or give value using init block which is use initialize the property of class. or you can also give declare as optional with ? var x : Int?

override init() {
super.init()
a = 0
}
Sahil
  • 9,096
  • 3
  • 25
  • 29
1

Swift performs Two phase initialization :

Two-Phase Initialization
Class initialization in Swift is a two-phase process. In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.”

Basically, this means that a property is not ready for use till it is provided an initial value.

In Objective-C, this was handled internally as the properties were set nil or 0 (depending on the data type) until initialized.

This behavior is provided by Optionals in Swift.

“You use optionals in situations where a value may be absent. An optional says:

There is a value, and it equals x or

There isn’t a value at all”

As mentioned by other answers, you can declare an optional using a "?"

eg: var a : Int?

For details refer : The Swift Programming Language (Swift 2.2).

UditS
  • 1,936
  • 17
  • 37