在Swift中我们可以比较选项,我们也可以比较字典,但如何比较可选的字典?
var dict: [String: String]? = [
"name" : "A name",
"email" : "an@email.com"
]
var dict2 = [
"name" : "A name",
"email" : "an@email.com"
]
if dict2 == dict { // Error line: Value of optional type '[String : String]?' not unwrapped; did you mean to use '!' or '?'?
}
这不会编译并强制我们打开字典。任何干净的解决方案?
答案 0 :(得分:1)
取消您的字典实例,然后尝试比较它。
使用if-let
阻止
let dict: [String: String]? = [
"name" : "A name",
"email" : "an@email.com"
]
let dict2 = [
"name" : "A name",
"email" : "an@email.com"
]
// use if-let
if let dict1 = dict, dict2 == dict1 {
print("true") // result is "true"
} else {
print("false")
}
字典'name'的更新值
let dict3 = [
"name" : "B name",
"email" : "an@email.com"
]
// use if-let
if let dict1 = dict, dict3 == dict1 {
print("true")
} else {
print("false") // result is "false"
}