Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift destructure an optional tuple to individual optional values

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

like image 281
Steve Kuo Avatar asked Oct 30 '22 01:10

Steve Kuo


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

like image 105
Martin R Avatar answered Nov 15 '22 05:11

Martin R