Swift supports destructuring.
func pair() -> (String, String)
let (first, second) = pair()
Is there a way to destructure an optional tuple to individual optional values?
func maybePair() -> (String, String)?
let (maybeFirst, maybeSecond) = maybePair()
Such that maybeFirst and maybeSecond are optional strings (String?).
A possible solution (thanks to @dfri for simplifying my original attempt):
let (a, b) = maybePair().map { ($0, $1) } ?? (nil, nil)
If the return value from maybePair() is not nil, the closure is
called with $0 as the unwrapped return value, from which a
(String?, String?) is created. Otherwise map returns nil
and the nil-coalescing operator evaluates to (nil, nil).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With