This is why it's lame that Swift's optionals are a language feature and not an in-language implementation.
In Haskell, optionals are Monads, which means there is a function
join :: m (m a) -> m a
"Maybe" (Haskell's standard library Optional) is a monad, so you can unwrap/collapse them using Join.You can also daisy-chain them together using >>=, a la
fail1 :: Maybe a
fail2 :: a -> Maybe b
result = fail1 >>= fail2
If either fail1 or fail2 fails, the entire "result" function fails (i.e. returns "Nothing"). enum Foo {
Bar,
Baz(i32),
Qux(f64)
}
if let Bar = item {
// do something
} else if let Baz(val) = other {
// do something with val
}
which is oft shorter than a full-blown `match`, and more convenient when alternating on different "source" items.https://github.com/rust-lang/rfcs/blob/master/text/0160-if-l...
I am glad to see Swift 1.2 expanding "if let" to multiple clauses. But I do wish it supported arbitrary values instead of just Optional.
(if-let [name name-whose-value-is-possibly-null]
(something-to-do name))
[0] https://clojuredocs.org/clojure.core/if-let if (mytype* p = find_or_null(blah))
foo(*p);
Still have to dereference p, but at least it's only in scope when doing so is safe. Also goes well with auto and std::optional: if (auto opt = find_or_none(blah))
foo(*opt);See the Rust RFC on the subject for motivations and comparisons: https://github.com/rust-lang/rfcs/blob/master/text/0160-if-l...
case result of
Just x -> <do something with x>
Nothing -> <do something without x>
This works with optionals as well as any other algebraic data type.Personally, I appreciate that the language naturally makes me organize my code better and more safely.
switch optional {
case .Some(let numeral):
println("Caught a \(numeral)")
default:
println("Nothing to catch")
}The "wrapping the optionals in a tuple and using switch to pattern match" hack always seemed dirty, and this is a huge step in the right direction for code readability.
Translation for those unfamiliar with Swift: Swift has a relatively strong type system. If a variable in Swift can be null at any point, it must be explicitly declared so as part of its type (e.g. an integer that can be null has the type "Int?", an integer that cannot be null has the type "Int").
Swift has a way to 'unwrap' these optional values and do things with them if they exist. Prior to this release, unwrapping multiple optional things required a bunch of nested if statements. With this release, unwrapping multiple optional values can be done in one if statement.