Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

short 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.



Note that it's no longer "would," this is a feature included in this beta. OP's code is now legal.


often times you want to do more stuff in either case so ? does not always work. The if-else approach is more general.


You could also do this:

    let x: Something = {
      if condition {
        someSideEffect()
        return foo()
      } else {
        anotherSideEffect()
        return bar()
      }
    }()
But it's kind of ugly.


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


That'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.


Let's hope you don't have a baz.


you can torture the logic further:

let x : Something = outer_conditional ? baz() : conditional ? foo() : bar()


I think this can look pretty nice, properly formatted:

    let x = conditional1 ? bar() :
            conditional2 ? baz() :
            conditional3 ? quux() :
            someDefault




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: