【发布时间】:2016-06-24 13:03:17
【问题描述】:
我认为这是可能的,但似乎无法让它发挥作用。我确定我只是在愚蠢。我试图以
的形式输出格式化的地址"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)")
}
【问题讨论】:
-
print("\(one ?? ""),\(two ?? ""),\(three ?? "")"),也许吧。 -
如果一些但不是所有变量都为零,您期望什么输出?
if one ?? two ?? three != nil检查是否至少有一个非零,但不展开。[one, two, three].flatMap { $0 }给出非零变量的列表,展开。 -
我以“不清楚您的要求”投票结束,但如果问题更新,我很乐意撤销投票。
-
@MartinR 对任何混淆感到抱歉。我试图从一组可选组件(地址、城市、国家等)中输出格式化的地址(以“地址、城市、国家/地区”的形式)。如果城市为 nil,则输出将为“地址、国家/地区”。看起来你的 flatMap 想法会起作用
-
@Danny:我撤回了我的最后一票,但您应该更新 question 本身以澄清您的问题(没有人会阅读所有 cmets)。