Understanding Collection Types in Swift Part 2

Keith Elliott (keithelliott.co)
Swift Programming
Published in
7 min readMar 13, 2016

--

In Part 1 of this series, we covered Arrays and Sets — two of the collection types in Swift. We hit the highlights and went over how they are similar and where they differ. In this article, we will discuss Set operations and cover Dictionaries as a collection type.

If you didn’t read part 1, do that before reading this article to make sure you get the background on Arrays and Sets.

Set Operations

Set operations are functions that provide comparison insights on two Sets when viewed together. Set operations perform tasks such as checking if two collections have common values, determining if one collection is just a subset of another, or combining them together.

Core Set Functions

It’s been a long time since I took Set Theory in school. The non-“maths” description is that Set Theory is about comparing collections against each each other to test for equality, overlaps, and differences. For us, the gist is that Set operations in Swift allow us to make many of the same comparisons using a few method calls. With that, let’s dive in.

Intersection — The intersect(:) method will return a new set that contains just the values common to both sets.

Set operation — intersect

ExclusiveOr — The exclusiveOr(:) method will return a new set populated with items that aren’t in either of the sets used for comparison. This is essentially like negating the Intersection method.

Set operation — exclusiveOr

Union — Swift also defines the union(:) method to combine two sets. The returned set from this method has all of the items from the two sets under comparison.

Set operation — union

Subtract — Swift’s subtract(:) method returns a new set that will remove all of the values contained in Set B from Set A.

Set operation — subtract

Supersets and Subsets — Testing for Equality

When working with collections, it is often useful to know if one collection’s values contain all of the same values of another’s. We can extend this line of questioning to ask if collection A has all of the same values as collection B plus more. Swift Sets allow us to determine a set’s membership in relation to another set. Swift Sets can determine if two sets are equal, meaning they contain all of the same values, or if they just have some values in common.

operator(==) — Use to determine if two sets have exactly the same values.

Set operation (== operator)

isDisjointWith(:) — Use to determine if two sets have any values in common.

isSubsetOf(:) — Use to determine if the Set A is a subset of Set B, meaning that of the first set’s values are contained in the compared set.

isSupersetOf(:) — Use to determine if of the compared set’s values are in the calling set.

Set operations — subsets and supersets

A keen observer will notice that there are two additional methods in the source above (isStrictSubsetOf and isStrictSupersetOf). These two methods test to see if a set is a subset or superset, respectively, but they also add the requirement that the two sets are not equal. Since the sets above are equal, our isSubset and isSuperset methods will both return true. Using the strict versions of the methods, our results are false because the sets are equal. Adding an item to Set A changes our results because the sets are no longer equal.

Set operations — strict subsets and superset

Dictionaries

A Swift Dictionary is a collection that stores key-value pairs. The key is a unique type that is used to find it’s associated value. The key must be unique in a dictionary. However, the value associated with a key doesn’t have to be distinct. The same value could be stored multiple times in the dictionary. Dictionaries are not ordered collections, meaning they don’t store their key-value pairs in any guaranteed order. Note this difference from arrays. You’ve been warned! You access a dictionary’s value by referencing its key.

Creating Dictionaries

We can create an empty Dictionary by providing type information for both the key and value.

You can also create a Dictionary using literals, as shown below. Dictionary literals need to be written as key and value combinations separated by “:”. Each key-value pair is separated by a comma, and the entire literal is contained within square brackets.

Similar to Arrays and Sets, Dictionaries have count and isEmpty properties to return a dictionary’s count and boolean value on whether the dictionary contains any values.

Manipulating Dictionaries

Swift Dictionaries access their values by referencing a key. Using a key, we can retrieve the value, update the value, or add a new key value pair to the dictionary if no key already exists. Swift Dictionaries also have an updateValue(:forKey:) method that you can use instead of subscripting. The updateValue(:forKey:) returns the old value or nil (for inserts), which could be helpful in confirming that the value was actually updated.

Swift Dictionaries — Insert and Updates

You can remove values from the Dictionary using either subscript syntax or with the removeValueForKey(:). When using subscript syntax, assigning a key to nil will remove the key-value pair from the dictionary. The removeValueForKey(:) method not only removes the key-value pair, but also returns the removed value or nil if the value never existed.

Swift Dictionaries — Removing Values

We can also iterate over Dictionaries using the for-in construct. Each iteration is assigned to a key-value tuple, which you can access in the body of the loop. As I mentioned earlier, Dictionaries are not sorted or ordered collections. However, you can access either the keys or values properties to get arrays with which you can work. For instance, you can use the sort() method on the keys property and then iterate over a sorted array of keys. During each iteration, you would then use subscripting to access the value stored for a key. The result is sorted access to a dictionary.

Swift Dictionaries — Iterating over Dictionaries

Final Thoughts

This article covered Set operations and Dictionaries. Including the previous article, we have covered the basics of collections (Arrays, Sets, and Dictionaries) using Swift. Still, I have one last part that I think you will find interesting. In Part 3, we will discuss how you can make your classes and structs behave like collections. If you want to experiment with the Playground for Swift Collections, you can find it here.

On a lighter note, I also wrote an article on why creating native apps is probably the best way to go in most of your mobile development endeavors. Read it and weigh in the discussion!

Or check out my article on the common traits Rockstar developers possess.

If you find this post helpful, please recommend it for others to read. You can visit me at www.gittielabs.com and subscribe to my RSS feed so that you won’t miss a post. I’m also putting together a video course to teach Swift development and could use your input on topics you feel would be helpful. Thanks for reading!

--

--

Keith Elliott (keithelliott.co)
Swift Programming

Tech vet, 20+ yrs from dev to CTO, startup enthusiast, husband, father of 5 + foster child. Eager to empower startups and motivate devs, thriving amid chaos.