4 ms·
When I'm reading code, I may not realize that an expression can return, because it can be hard to spot a ? embedded in the middle of the line: sanitize(get
by millstone 8y ago
When I'm reading code, I may not realize that an expression can return, because it can be hard to spot a ? embedded in the middle of the line:
sanitize(getFile(getName())?.contents);
Swift requires prefixing the line with try, which makes it easier to notice:
try sanitize(getFile(getName()).contents)
Both are a big improvement over exceptions which have no indication at the call site.
- eridius 8y agoIn Swift you can still bury that `try` in the middle of the expression sanitize(try getFile(getName()).contents)
- kibwen 8y agoBit of a correction, I believe that `try` in Swift must precede an expression that can throw, rather than preceding a statement that can throw, so AFAICT the Swift code would have to be written like this: sanitize((try getFile(getName())).contents) This sort of illustrates why Rust moved away from its own prefix `try!` macro to its postfix `?` operator: in a language that encourages chaining methods, `foo()?.bar()?.qux()?` looks better than `try!(try!(try!(foo()).bar()).qux())`.
- dbaupp 8y agoNo, `try` can be applied to any expression, and will "try" all throwing calls in subexpressions of that: func f() throws -> Int { return 0 } func nothing(_ x: Int) {} func g() throws { nothing(try f()) try (f() + f()) try nothing(f() * f()) } This includes method chains: struct Foo { init() throws {} func bar() throws -> Foo { return self } func qux() throws -> Foo { return self } } try Foo().bar().qux()
- kibwen 8y agoCool, thanks, I looked in the official docs but didn't notice any mention of this feature. :)
- eddyb 8y agoNot sure how many editors' syntax highlighting do this by default, but at least for me, it really helped to make `?` bold red.