简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM