【问题标题】:How to compare optional Dictionaries? Swift 3如何比较可选字典?斯威夫特 3
【发布时间】:2017-06-27 13:21:50
【问题描述】:

在 Swift 中我们可以比较 optionals,我们也可以比较字典,但是如何比较 optional Dictionaries?

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

}

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

【问题讨论】:

  • dict2 == dict 是一个逻辑评估,而不是一个赋值...... dict 是一个未包装的可选,而dict2 已被包装 最初......那么你想在这里实际做什么?
  • Why is Equatable not defined for optional arrays 中的问题基本相同——仅针对字典而不是数组。
  • 最简洁的解决方案是将此数据表示为结构。在这里使用字典有什么特别的原因吗?

标签: swift dictionary compare optional


【解决方案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")
}

字典“名称”的更新值

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 3 中不受支持。我可能没有正确表达我的问题。答案在@MartinR 在对我的问题的评论中给出的链接中:link。不过,由于您愿意帮助其他程序员,我会接受您的正确回答!
猜你喜欢
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多