简体   繁体   中英

How to compare optional Dictionaries? Swift 3

In Swift we can compare optionals, we can also compare dictionaries, but how to compare 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 '?'?

}

This doesn't compile and forces us to unwrap the dictionary. Any clean solutions?

Unwrapp your dictionary instance and then try to compare it.

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

Updated value of dictionary '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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM