Rushi Rushi - 7 months ago 12
Swift Question

Why latest Swift version always says variable is not initialized before use

take 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.

Answer

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
}