Swift 展开多个可选值

Swift unwrapping for multiple optionals

我认为这是可能的,但似乎无法让它发挥作用。我确定我只是在装傻。我正在尝试以

的形式输出格式化地址
"one, two, three"

来自一组可选组件(一、二、三)。如果 "two" 为 nil,则输出为

"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)")
}

我不知道你为什么需要这个,但接受它 =)

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

如果您尝试将非 nil 值打印为逗号分隔列表,那么我认为 @MartinR 使用 flatMap() 的建议是最好的:

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

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

let nonNils = [one, two, three].flatMap { [=10=] }
if !nonNils.isEmpty {
    print(nonNils.joinWithSeparator(","))
}

输出:

one,three