I think the best way to express this today is with Optional.map
:
let result = x.map { f($0) } ?? defaultValue
EDIT: Expressed even more concisely by @Jon_Shier above.
which avoids the multi-place initialization and the force unwrap. That said, I like the look of the if
expressions, and would like to at least explore this direction. It also seems somewhat relevant to bring up the Implicit Returns from Single-Expression Functions pitch because of the single-expression limitation of this pitch. Are there other places where a single expression in a block could allow for a statement to expression conversion?
Also, it's possible today to expression-ize any statement by doing the following:
let result = { if let x = x { return f(x) } else { return defaultValue } }()
// EDIT: Currently, type inference can't handle the above closure,
// so we're actually forced to specify `result: Int`. Is this something
// that is expected to improve?
Are there benefits we would gain aside from a slightly more terse syntax?