As I said, it is also problematic when function evaluation is at the end of the chain, and that I wish such call sites would complain that the result is unused. E.g. someOptionalCollection?.forEach { ... }
returns nil
if the the collection is nil, and .some(())
if the collection is non-nil, so there is a return value which is silently discarded and obfuscates the fact that there is a no-op branch in there.
However, most use cases for optional chaining is to walk a property path, evaluate each node, and return the leaf node wrapped in an optional. That is, we still have an optional.
The result of optional chaining is always an Optional
, and using it almost always requires the usual ceremony where optional values are involved. That is, binding it, unwrapping it, guarding on it, pattern matching it, or whatever. This ceremony is usually very visible and easy to read:
if let foo = some.long?.winded.path?.of.optionals {
// it's pretty obvious that we're dealing with branching here
}
But it still removes the clutter of unwrapping each node along the path:
if let long = some.long, let path = long.winded.path, let foo = path.of.optionals {
// the branching is here is obvious as well, but the clutter doesn't add much in terms of clarity
}
I don't think all optional chains are bad.
However, the branching and implicit no-op here is obfuscated at a glance:
for item in some.long?.winded.path?.of.optionals {
// it's clear that this is a loop, but not that it is wrapped
// in an implicit if-branch, with a no-op path
}
I don't think you can convince me otherwise. You can perhaps convince me that the feature is worth the cost, if the motivation is compelling enough, but so far I don't see it. Either wrapping the iteration in an if-let
, or appending ?? []
, or creating an extension on Optional where Wrapped: Sequence
that returns some kind of OptionalIterationSequence<Wrapped.Element>
or whatever, is probably a better solution, IMHO.
I think I have voiced my concern with this pitch, and I don't think it is fruitful for the discussion to spend much more time on me. Either let the discussion progress with other aspects of the pitch, or address my concerns with better motivations.