Swift - Testing Dictionaries for Equality

Introduction

You can test the equality of two dictionaries using the == operator.

Two dictionaries are equal if they contain exactly the same keys and values, as the following illustrates:

Demo

var dic1 =  [
   "1": "a",
   "2": "b",
   "3": "c",
]

var dic2 =  [//from  w  w  w  . j  a v  a2 s.  c o m
   "3": "c",
   "1": "a",
]


print("Equal: \(dic1 == dic2)")  //false

Result

The preceding expression evaluates to false, as the two dictionaries do not contain the same exact number of keys and values.

However, if you add a new item to dic2 , then it will evaluate to true :

dic2 ["2"] = "b"
print("Equal: \(dic1 == dic2)")  //true

Related Topic