This is practical. It's something you wish for within a couple hours of Swift.
let x : SomeThing
if condition {
x = foo()
} else { x = bar()
}use(x)
let x : SomeThing
if condition {
x = foo()
} else { x = bar()
}use(x)
const int a = [=](){
//do stuff here that returns an int:
if (condition) { return foo(); } else { return bar(); }
}();
Does this idiom work in swift? let x: String = {
if 3 == 4 {
return "Hello"
} else {
return "Goodbye"
}
}()
Although in this case, I'd just use ternary. let x = (3 == 4) ? "Hello" : "Goodbye"let x : Something = condition ? foo() : bar()
but yeah, it would be nice to defer initialization of an immutable.
let x : Something = outer_conditional ? baz() : conditional ? foo() : bar()
let x = conditional1 ? bar() :
conditional2 ? baz() :
conditional3 ? quux() :
someDefault let x: Something = {
if condition {
someSideEffect()
return foo()
} else {
anotherSideEffect()
return bar()
}
}()
But it's kind of ugly. let x: Something = if condition {
// do stuff
foo()
} else {
// do other stuff
bar()
}