Swift Collections — Part 1 (Arrays and Sets)
There are three collection types in the Swift language: Arrays, Sets, and Dictionaries. In general, a collection type is a way to group related items together. Arrays provide a way to make ordered lists of related items. Sets allow you to create distinct unordered lists, meaning you can’t have duplicate entries in your group. Dictionaries are groupings of key-value pairs. Each solves a particular type of grouping problem and are important in their own right. To make sure we don’t exhaust all of the good stuff in one article, I will to cover everything in a series. In this article, we will cover Arrays and Sets. In the next article, we will cover advanced Set operations and explore the last collection type Dictionaries.
Swift’s array, set, and dictionary types are implemented as generic collections. For more on generic types and collections, see Generics.
Collections are immensely important to every programming language. Grouping related items and further manipulating the grouping is at the heart of working with data. Swift offers us ways to create mutable (changeable) and immutable (not changeable) variants of collections.
We are allowed to loop over our collections to access the indices and extract, insert, or even delete items. It would be pretty hard to create a useful application without have some form of collection — most likely several in practice!
Working With Arrays
Swift Arrays are created using the Generic type Element. The formal definition of a Swift array is defined as Array<Element>, with the Element being a single type used in the collection. Once you define the type, you can't add any other type to the array or you will get a compile-time error.
Creating Arrays
Arrays are easy to create. You can create an array with the type explicitly set or allow the Swift compiler to infer the type.
Since the Swift compiler can determine types based on context, you can simplify syntax and skip providing a type for an array when creating one. Just remember that once an array is defined, you can’t redefine it to be a different type.
You can also create an array and initialize it with values. In fact, there are several ways to create an array with initial values. The most common way is to assign an array literal. An array literal is defined using the following syntax:
[value1, value2, value3]
In the following, I define a list of Apple operating systems as an array literal and assign the list to create the os array.
A lesser known way for creating an array is to set it’s initial size and add default values. Let’s say you wanted to have a list of Int values to represent counters. It would be interesting to both set the number of counters in the list and default each value in the list to zero. Well, you’re in luck because it’s very easy to do that with Swift Arrays.
You can also create an array by adding two arrays together — provided they have the same type.
Manipulating Arrays
Now that we know how to create arrays, we can move on to using them. Arrays have several methods and properties to allow you to access values or even to insert or remove values. You can determine how many elements are in an array using the count property. Or if you’re interested if an array has any values at all, you can use the isEmpty property to retrieve a true/false value on the array state.
Adding and removing values are straightforward with arrays. You can add values to the end of an array using the append(:) method, or you can insert a value into an array at a specified index using the insert(:atIndex:) method.
With Swift arrays, we can access an index to retrieve or replace its value.
You can retrieve a subarray using subscript syntax.
let mycars = car_brands[0...2]
// mycars = ["BMW", "Nissan","VW"]
You can remove items from an array using the removeAtIndex(:) method.
Finally, you can iterate over an array using the for-in syntax.
If you need the index along with the item, you can use the enumerate() method to loop over an array. Each item of the array is returned along with its index using a tuple to store both values.
Working with Sets
Sets are similar to arrays but differ in a few ways. Sets store distinct values and are unordered lists — i.e. you can’t guarantee order of the listed items. In addition, a Set can only take types that conform to the Hashable protocol, which allows the set to test that each item it holds is distinct. All of the foundation types are Hashable and can be used with Sets. If you want to use one of your own classes or structs with a set, you will need to implement the Hashable protocol.
Creating Sets
Creating a set is very similar to creating an array.
You need to include the Set keyword since the Swift compiler cannot infer that you want a Set over an array when using array literals.
The shorthand syntax in the example above works because the array literal contains items of the same type, giving the Swift compiler the right hints to infer Set<String> as the property type.
Manipulating Sets
Since Sets behave like arrays, it’s not surprising that they have similar accessors. The count and isEmpty properties work exactly the same as for arrays. The insert and remove methods are very similar. Since Sets aren’t ordered collections, there is no need to require an index. You just add or remove them from a Set since you are guaranteed to insert or remove at most one item. You can also use the contains(:) method to see if an item is in the Set.
As you might expect, iterating over a Set works like it does for arrays. You use the for-in syntax for general looping. However, since Sets aren’t ordered, you have to sort the Set if you want the list to be in a particular order before iterating over it.
Sets are useful but often underused. In part 2, we will cover Set operations and hopefully give you some ideas on how to use them in your code.
Final Thoughts
Today we learned about Arrays and Sets. We covered a lot, but we still have more to go on Sets and Dictionaries. I hope you will read part 2 to get the complete picture.
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. Please read that one and weigh in the discussion!
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!