Getting Started With the Swift Collections Package

Learn about three new data structures available in the Swift Collections package: Deque, OrderedSet and OrderedDictionary. By Felipe Laso-Marsetti.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Knowing When to Use OrderedDictionary

Use OrderedDictionary when it's imperative to maintain the order of elements in your dictionary. But remember, even though OrderedDictionary is powerful, it has limitations.

Because OrderedDictionary has to maintain unique keys, the elements of the dictionary don't conform to MutableCollection or RangeReplaceableCollection. If your code relies on conforming to either of those protocols, you'll need to find an alternative.

Although OrderedDictionary doesn't conform to these protocols, it still supports mutations, or modifications, that change the order of its elements or remove a subset of its existing elements.

To insert elements efficiently, OrderedDictionary implements reserveCapacity(_:).

The performance of your OrderedDictionary, like Dictionary, depends on your key's implementation of Hashable.

Finally, Swift Dictionary literals are also ordered. As they are built into the language, like KeyValuePairs, they offer a good alternative to OrderedDictionary that doesn't require importing the Swift Collections package.

Ordered Dictionary vs. Dictionary

And that's it! Congratulations on finishing the tutorial. You should now have a clear understanding of three new tools from the Swift Collections package.

Where to Go From Here?

Download the final project by clicking the Download Materials button at the top or bottom of this tutorial.

You can expand your knowledge by working with collections in your own apps and by checking out the following resources:

  • You can find the entire Swift Collections GitHub repository and documentation here.
  • Read the Data Structures and Algorithms in Swift book. You'll not only learn how a lot of common data structures and algorithms work, but also how to write your own.
  • You can also peruse the Swift Algorithms Club web page. It will teach you how to implement popular algorithms and data structures in Swift

This tutorial was a mere glimpse into Apple's new Swift Collections package. You can expect this package to expand in the future as more specialized collection types are added.

Thanks for reading this tutorial. We hope you enjoyed it. If you have any questions or comments, please leave a comment in our forums. Till next time!