5 ms·
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
by melling 12y ago
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)
- bigdubs 12y agoshort of having a language mechanism for doing an 'uninitialized' let, conditional operators could work: let x : Something = condition ? foo() : bar() but yeah, it would be nice to defer initialization of an immutable.
- jafingi 12y agoLet's hope you don't have a baz.
- LinaLauneBaer 12y agooften times you want to do more stuff in either case so ? does not always work. The if-else approach is more general.
- matt_kantor 12y agoYou could also do this: let x: Something = { if condition { someSideEffect() return foo() } else { anotherSideEffect() return bar() } }() But it's kind of ugly.
- masklinn 12y agoSad that Swift doesn't use an expressive if, then you could just write: let x: Something = if condition { // do stuff foo() } else { // do other stuff bar() }
- 0942v8653 12y agoThat's something I really miss in other languages—the ternary operator is just not good enough for when you have a condition like this. In lisp it's 3 lines which is just the right amount when in other languages you have 6 lines (and until now unnecessary mutability) or only one.
- mikeash 12y agoNote that it's no longer "would," this is a feature included in this beta. OP's code is now legal.
- netcraft 12y agoI wish the es6 const would allow this.
- spott 12y agoso, in c++ you can do initialization of const value via lambda closures that are immediately evaluated: const int a = [=](){ //do stuff here that returns an int: if (condition) { return foo(); } else { return bar(); } }(); Does this idiom work in swift?
- deleted 12y ago[deleted]
- lyinsteve 12y agolet 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"