Search code examples
swiftoption-typeunwrap

Swift unwrapping for multiple optionals


I thought this was possible but can't seem to get it to work. I'm sure I'm just being stupid. Im trying to output a formatted address in the form of

"one, two, three"

from a set of optional components (one, two, three). If "two" is nil then output would be

"one, three"

let one: String?
let two: String?
let three: String?

one = "one"
two = nil
three = "three"

if let one = one,
        two = two,
        three = three {
     print("\(one),\(two),\(three)")
}

Solution

  • If you're attempting to print the non-nil values as a comma-separated list, then I think @MartinR's suggestion of using flatMap() is the best:

    let one: String?
    let two: String?
    let three: String?
    
    one = "one"
    two = nil
    three = "three"
    
    let nonNils = [one, two, three].flatMap { $0 }
    if !nonNils.isEmpty {
        print(nonNils.joinWithSeparator(","))
    }
    

    Output:

    one,three