cdeerinck
cdeerinck

Reputation: 796

Setting an immutable variable with conditional logic in Swift

I have a super simple question on the best way (i.e. style) to do this correctly in Swift.

if a > b {
    let x = 1
} else {
    let x = 2
}
//then procede to use x

Obviously, this will not work, because the scope of x is only within each branch of the if. But what is the preferred way to go about this, if I want x to be immutable? So far, I have been doing this:

var x:Int
if a > b {
    x = 1
} else {
    x = 2
}
//then procede to use x

which works, but leaves x as mutable. The next choice is to use the ternary operator as in:

let x = a > b ? 1 : 2

This leaves x immutable but leaves a bit to be desired in terms of readability when the conditions and resulting values become complex. Also, using the ternary solution completely falls down with a more complex example:

if a > b {
    let x = 1
} else if b > c {
        let x = 2
    } else {
        let x = 3
    }
}
//procede to use x

or this:

switch a {
case 1:
    let x = 1
case 2:
    let x = 2
default:
    let x = 3
}
//procede to use x

Is their any way to promote the scope of a let outward one level, or some other way this type of situation is normally handled?

Upvotes: 2

Views: 906

Answers (2)

Jaimin
Jaimin

Reputation: 141

you can also achieve it using class. like this

class immutableVariable{
    private var value: Any

    init(newValue: Any = "") {
        self.value = newValue
    }

    func changeValue(withNewValue newValue: Any){
        self.value = newValue
    }

    func getValue() -> Any{
        return value
    }
}

and then call it like

let x = immutableVariable()

if a > b{
    x.changeValue(withNewValue: 1)
}else{
    x.changeValue(withNewValue: 2)
}

and access values using

print(x.getValue())

Upvotes: 1

rmaddy
rmaddy

Reputation: 318814

You can use let in your 2nd example:

let x:Int
if a > b {
    x = 1
} else {
    x = 2
}

As long as x is fully initialized in all paths, this works.

It works with the switch as well:

let a = 3
let x: Int
switch a {
case 1:
    x = 1
case 2:
    x = 2
default:
    x = 3
}

Upvotes: 3

Related Questions