error handling - swift, optional unwrapping, reversing if condition -
error handling - swift, optional unwrapping, reversing if condition -
let's have function returns optional. nil if error , value if success:
func foo() -> bar? { ... }
i can utilize next code work function:
let fooresultopt = foo() if allow fooresult = fooresultopt { // go on right operations here } else { // handle error }
however there few problems approach non-trivial code:
error handling performed in end , it's easy miss something. it's much better, when error handling code follows function call.
correct operations code indented 1 level. if have function call, have indent 1 more time.
with c 1 write this:
bar *fooresult = foo(); if (fooresult == null) { // handle error , homecoming } // go on right operations here
i found 2 ways accomplish similar code style swift, don't either.
let fooresultopt = foo() if fooresult == nil { // handle error , homecoming } // utilize fooresultopt! here allow fooresult = fooresultopt! // or define variable
if i'll write "!" everywhere, looks bad taste. introduce variable, doesn't either. ideally see following:
if !let fooresult = foo() { // handle error , homecoming } // fooresult has bar type , can used in top level
did miss in specification or there way write looking swift code?
your assumptions correct—there isn't "negated if-let" syntax in swift.
i suspect 1 reason might grammar integrity. throughout swift (and commonly in other c-inspired languages), if have statement can bind local symbols (i.e. name new variables , give them values) , can have block body (e.g. if, while, for), bindings scoped said block. letting block statement bind symbols enclosing scope instead inconsistent.
it's still reasonable thing think about, though — i'd recommend filing bug , seeing apple it.
swift error-handling optional
Comments
Post a Comment