Home > Blockchain >  Variable used before being initialized with if statement
Variable used before being initialized with if statement

Time:02-17

It’s strange but when I want to run this code :

func test () {

var a: Int
let b = true
var c: Int

if b {
    a = 10
}

c = a * a

}

It says « variable a used before being initialized ».

So I need to implement else statement :

func test () {

var a: Int
let b = true
var c: Int

if b {
    a = 10
} else {
    a = 0 // will never be executed
}

c = a * a

}

It says logically that else will never be executed. But then why do they force me to implement else statement ?

CodePudding user response:

You need to add an initial value to the variable by declaring the variable as Int() it assigns the value 0 by default.

By making this line change everything works for me: var a: Int --> var a = Int()

func test() {
    var a = Int()
    let b = true
    var c: Int
    
    if b {
        a = 10
    }
    c = a * a
}

With the help of this you don't need to add esle part.

CodePudding user response:

as the previous response said, because of the if b a may not be initialised, the simplest solution is to just give a a default value, but if you don't want it to be changed after being initialised you can provide and else instead for example

func test () {

    let a: Int
    let b = true
    var c: Int

    if b {
        a = 10
    } else {
        a = 0
    }

    c = a * a    
}

You can see the a is defined as let, and once set in the if or else its value is set.

  • Related