BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

When to use a set rather than an array

Swift version: 5.10

Paul Hudson    @twostraws   

Sets and 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.

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Available from iOS – learn more in my book Pro Swift

Similar solutions…

About the Swift Knowledge Base

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

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.6/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.