UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

When to use a set rather than an array

Swift version: 5.6

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.

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

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