I feel uneasy about adding methods to Optional
. Optionals are mostly interacted with using overloads, operators, and syntax sugar in Swift. Correctly, every time I use map
on an Optional
feels like I am making the code more difficult to read for future me.
For example, an Int
does not have a map
method, so if I read something like counter.map { $0 + set.count }
I get that counter
is actually an Int?
. But String
, Array
, etc. also have map
methods and now when I am bug hunting I am reading such code much more slowly, checking if (…).map { … }
should have been (…)?.map { … }
.
isKnownIdentical
falls even more so into this trap since every optional type for which (…).isKnownIdentical(to: …)
is valid code, so too is (…)?.isKnownIdentical(to: …)
.
The later case ((…)?.isKnownIdentical(to: …)
) may also be typed accidentally. This returns nil
if the lhs
is nil
, even when the rhs
might also be nil
and thus the return value should be true
. A freestanding function doesn’t suffer from this confusing call site.
If I understand Span
correctly, this only works for contiguous memory, not necessarily a Dictionary
or some tree structure which cannot provide a span view.