NEW: My free 100 Days of SwiftUI challenge starts tomorrow! >>

What are sets?

Swift version: 5.0

Paul Hudson    @twostraws   

Sets are a type of sequence similar to arrays, except they may not store any item more than once and are unordered. This eliminates them from many places where you would use an array, but they do have one special super-power: it’s extremely fast to check whether a set contains a specific value. In fact, sets perform this operation at the same speed whether they contain 10 items or 10,000 items.

Sets can be created directly from arrays, then used like them in many ways. For example:

var numbers = Set([1, 2, 3])

You can then go ahead and check whether that contains a specific value, like this:

print(numbers.contains(5))

Because sets don’t have any concept of ordering, they don’t have an append() method. Instead, they use insert(), like this:

numbers.insert(5)

LEARN SWIFTUI FOR FREE I wrote a massive, free SwiftUI tutorial collection, and also have a growing list of free SwiftUI tutorials on YouTube – get started today!

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!