NEW: Master Swift design patterns with my latest book! >>

When to use a set rather than an array

Written by Paul Hudson    @twostraws

Sets an arrays both store objects of your choosing, but they have four important differences:

  1. Sets do not store objects in the order they add them.
  2. Instead, they are stored in a way to make them fast to find, which means finding items in sets is extremely efficient.
  3. Sets store each item precisely once.
  4. All items you want to store in a set must conform to Hashable.

As a result, you should use a set rather than an array if all the following criteria are true:

  1. You intend to add each item only once. Sets never allow duplicates.
  2. You don’t care about the order of the items in the set.
  3. You don’t need to use APIs that require arrays.
  4. You’re storing Hashable types, either your own or one of Swift’s built-in types likes strings and integers. Sets use hash values for fast look up of items.

You can switch between an array and a set simply enough:

let array = [1, 2, 3]
let set = Set(array)
let array2 = Array(set)

Using contains() on a set takes the same amount of time if you have one item as it does if you have one thousand items – it’s called an O(1) operation.

Available from iOS – learn more in my book Pro Swift

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Love Hacking with Swift?

Get all 40 projects in PDF and HTML: buy the Hacking with Swift book! It contains over 1300 pages of hands-on Swift coding, and will really help boost your iOS career

Click here to visit the Hacking with Swift store >>