Mastering Swift | Level up your Swift enum by… replacing it with an OptionSet?

What is an OptionSet & how and when to use it

John Baker
6 min readOct 31, 2023

Swift enums are a popular component in Swift for maintaining a unique identity (among other things). But their lesser known alternative go by the name of OptionSets.

What is an OptionSet?

Apple defines an option set as:

A type that presents a mathematical set interface to a bit set.

But what does that even mean?

An OptionSet is kind of like turning bits off or on in binary. So you define an ‘Option’ by defining it’s binary index in the definition. The use case for this might not be super clear up front, but it can allow an easy way to manage different settings & states across your application.

Lets take the example provided in Apple’s documentation (pay close attention to the commented code I added):

struct ShippingOptions: OptionSet {
let rawValue: Int

static let nextDay = ShippingOptions(rawValue: 1 << 0) // 0001
static let secondDay = ShippingOptions(rawValue: 1 << 1) // 0010
static let priority = ShippingOptions(rawValue: 1 << 2) // 0100
static let standard = ShippingOptions(rawValue: 1 << 3) // 1000


static…

--

--