Swift展开多个选项

时间:2016-06-24 13:03:18

标签: swift optional unwrap

我认为这是可能的,但似乎无法让它发挥作用。我确定我只是愚蠢。我试图以

的形式输出格式化的地址
"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)")
}

2 个答案:

答案 0 :(得分:3)

我不知道你为什么需要这个,但是把它当作=)

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

答案 1 :(得分:2)

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

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

输出:

one,three