Option Sets in Swift

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
July 15, 2023

Working with Option Sets in Swift

In Swift, an Option Set is a powerful tool for representing a collection of options or flags. It allows you to define a set of distinct values that can be combined using bitwise operations. Option Sets are particularly useful when you have multiple independent flags that you want to track and manipulate.

To create an Option Set in Swift, you first define a new custom type that conforms to the "OptionSet" protocol. Let's say we want to create an Option Set to represent different type of fruits:


struct FruitOptions: OptionSet {
    let rawValue: Int
    
    static let apple = FruitOptions(rawValue: 1 << 0)
    static let banana = FruitOptions(rawValue: 1 << 1)
    static let orange = FruitOptions(rawValue: 1 << 2)
    static let mango = FruitOptions(rawValue: 1 << 3)
}

In the above code snippet, we defined a new struct called "FruitOptions" that conforms to the OptionSet protocol. We also defined four static properties to represent different fruits. Each fruit is assigned a raw value using bitwise shift operators.

To create an instance of the Option Set and add or remove options, you can use the bitwise OR and XOR operators respectively. Here's an example:


var selectedFruits: FruitOptions = [.apple, .banana]

selectedFruits.insert(.orange)

if selectedFruits.contains(.apple) && !selectedFruits.contains(.mango) {
    selectedFruits.insert(.mango)
}

selectedFruits.remove(.banana)

In the above code, we created an instance of the FruitOptions Option Set and initially selected apple and banana as options. We then inserted the orange option using the insert(_:) method. Next, we checked if apple is selected but mango is not, then we inserted the mango option. Finally, we removed the banana option from the selectedFruits.

Option Sets provide a convenient and expressive way to work with multiple independent options in Swift. They allow you to perform operations like union, intersection, and subtraction on multiple options. Additionally, they provide type-safety and avoid the pitfalls of using raw values directly. Option Sets are commonly used in scenarios where you need to represent a collection of flags or options.

Summary: Option Sets in Swift provide a powerful way to work with multiple independent options or flags. They allow you to combine, manipulate, and check for presence of specific options using bitwise operations.