4 ms·
Something like a.?b.?c which is syntactic sugar for: a && a.b && a.b.c (with a short-circuiting &&.)
by omaranto 7y ago
Something like a.?b.?c which is syntactic sugar for:
a && a.b && a.b.c
(with a short-circuiting &&.)
- rimliu 7y agoThis is just optionals chaining, not nil coalescing.
- omaranto 7y agoThanks for correcting me, I actually wasn't aware of nil coalescing in Swift and guessed it meant the same thing as optional chaining. The nil coalescing operator seems to correspond to Haskell maybe function, that is, a ?? b is computed as follows: if a is nil, the result is b; otherwise a must wrap some actual value c and the result is c. Is that the one you had in mind?
- dtech 7y agoThis is Javascript/Typescript only, and not really correct. a?.b a && a.b will behave differently if a is false or 0 or an otherwise "falsy" value. It's identical to something similar though (a !== undefined && a !== null) ? a : b
- omaranto 7y agoThat's right, of course. I was just trying to convey the idea. But details matter of course. I was thinking of variables that either contained nil or contained an object with the appropriate field. If that precondition isn't meant you need more robust code like yours. But also, as another commenter pointed out, there is a distinction between "optional chaining" and "nil coalescing" and I explained (roughly) what optional chaining is.