Whilst going through Apple’s guide “Storing Keys in the Keychain” I noticed one thing.
The queries are of type [String: Any] , so I want to test the creation of the query.
I’ll need to test the keys and values of type String and Any are created correctly, respectively.
I’ll need to compare Any value types. :(
Any: An instance of any type, including function types
Dictionary: The association between keys and values (where all the keys are of the same type, and all values are of the same type)
Equatable: A protocol that can be applied to a type to allow value equality
Key-value pairs: A set of two linked data items, a unique identifier (key) and an item of data (value)
Creating a test to test the elements of a
Dictionary is ordinarily quite easy. We can simply use the equality operator (==) as long as the type is
Equatable (that is, the value conforms to the equatable protocol)
A Simple Comparison
If you wish to compare a
dictionary with [String: String] type (or any value types).
If the actual and expected
dictionaries are different (for either the key or the value), the equality (==) will return false. If they are the same, the equality will return true.
Within guide there is a section to “Create a Query Dictionary” addquery is setup as follows:
so I wish to calculate if this is equal to another
dictionary. However the type is [String: Any] and
Any does not conform to
That means even comparing the
Dictionary to itelf:
addquery == addquery
will generate an error like the following
We can extend the
equality operator and cast the Swift type
Dictionary to the Objective-C type NSDictionary where the values are Hashable.
Now by using this function we can compare the
dictionaries! Take a look at the full Playground as attached here
Any type does not conform to the
equality protocol. However, we shouldn’t let this stop us, and neither we will let it.
Making comparisons of
Dictionary types is extremely important, and can even be used when we create some tests while coding in Swift.
The Twitter contact:
Any questions? You can get in touch with me here