2

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?

1

2 Answers 2

3

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.