Swift version: 5.6
Sets and arrays both store objects of your choosing, but they have four important differences:
Hashable
.As a result, you should use a set rather than an array if all the following criteria are true:
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.
BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS – learn more in my book Pro Swift
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.