0

我认为这是可能的,但似乎无法让它发挥作用。我敢肯定我只是愚蠢。我试图以以下形式输出格式化地址

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

2 回答 2

3

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

if let _ = one ?? two ?? three {
    print("\(one),\(two),\(three)")
}
于 2016-06-24T13:10:10.433 回答
2

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

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
于 2016-06-24T14:13:13.100 回答