拥有一个可选值的字典通常不是一个好主意。字典使用nil 的分配作为您要从字典中删除键/值对的指示。此外,字典查找返回一个可选值,所以如果你的值是可选的,你最终会得到一个需要解包两次的双可选。
您可以使用分配nil 删除字典条目这一事实,通过仅分配值来构建[String : String] 字典。 nil 不会进入字典,因此您不必删除它们:
struct A {
var first: String?
var second: String?
var third: String?
}
let a = A(first: "one", second: nil, third: "three")
let pairs: [(String, String?)] = [
("first", a.first),
("second", a.second),
("third", a.third)
]
var dictionary = [String : String]()
for (key, value) in pairs {
dictionary[key] = value
}
print(dictionary)
["third": "three", "first": "one"]
正如@Hamish 在 cmets 中指出的那样,您可以为 pairs 使用 DictionaryLiteral(内部只是一个元组数组),这样您就可以使用更简洁的字典语法:
let pairs: DictionaryLiteral<String,String?> = [
"first": a.first,
"second": a.second,
"third": a.third
]
所有其他代码保持不变。
注意:您可以只写DictionaryLiteral 并让编译器推断类型,但我看到 Swift 无法编译或编译大型字典文字的速度非常慢。这就是为什么我在这里展示了显式类型的使用。
或者,您可以跳过pairs 的Array 或DictionaryLiteral,直接分配值:
struct A {
var first: String?
var second: String?
var third: String?
}
let a = A(first: "one", second: nil, third: "three")
var dictionary = [String : String]()
dictionary["first"] = a.first
dictionary["second"] = a.second
dictionary["third"] = a.third
print(dictionary)
["third": "three", "first": "one"]