gpt4 book ai didi

swift - 如何比较可选词典? swift 3

转载 作者:搜寻专家 更新时间:2023-10-31 22:56:55 25 4
gpt4 key购买 nike

在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 '?'?

}

这不会编译并强制我们打开字典。有什么干净的解决方案吗?

最佳答案

打开你的字典实例,然后尝试比较它。

使用if-let block

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

关于swift - 如何比较可选词典? swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44781412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com