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?