NEW: Nominations are now open for the 2019 Swift Community Awards! >>

When to use a set rather than an array

Swift version: 5.1

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.

SAVE 20% ON iOS CONF SG The largest iOS conference in Southeast Asia is back in Singapore for the 5th time in January 2020, now with two days of workshops plus two days of talks on SwiftUI, Combine, GraphQL, and more! Save a massive 20% on your tickets by clicking on this link.

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.

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift 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: 5.0/5