Friday, October 26, 2018

Flattening Nested Optionals Resulting From try?


Swift’s try? statement currently makes it easy to introduce a nested optional. Nested optionals are difficult for users to reason about, and Swift tries to avoid producing them in other common cases.

This document proposes giving try? the same optional-flattening behavior found in other common Swift features, to avoid the common occurrence of a nested optional.

John McCall:

How important is this problem to fix? It arises from a combination of two things: using the try? operator on a result that is already optional. This is, perhaps, not very common; it probably reflects two different methods of failure being used in one expression. But when it does happen, the extra optionality is almost always unwanted and causes significant friction for the programmer, demanding awkward workarounds: code like try? foo() has to be turned into something like (try? foo()) as? T. By forcing programmers to deal with the awkwardness of nested optionals more often, it raises the overall perceived complexity of working with optionals in Swift, and it makes try? feel unintuitive.

The Core Team does not want to make source-incompatible changes lightly, but we also want to leave room to improve the language for future users of Swift. We don’t have a bright-line rule for when a change crosses the line to become unacceptable, but the key consideration in our analysis is the change’s apparent impact in practice on existing code more than its hypothetical risks. In this case, we are convinced that the change leads to fairly inarguably better results.

I concur.

John McCall:

Casting doesn’t really “flatten”; it looks for any way in which it can interpret the operand value as the target type, and then wraps in a level of optionality to represent that that search can fail. But it’ll happily look through protocol types and so on. Any static behavior is going to seem inconsistent compared to that if you think of it as flattening, including the current behavior of try?.

2 Comments RSS · Twitter

So who shaves the barber?

[…] Flattening Nested Optionals Resulting From try? […]

Leave a Comment