Swift destructure an optional tuple to individual optional values

Viewed 2021

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?).

1 Answers

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).

Related