Member-only story
Mastering OptionSet in Swift
Simplifying Complex Sets of Options
OptionSet
is a protocol that allows developers to represent a set of options in a type-safe way.
It might be used for representing combinations of values in scenarios where multiple options might apply simultaneously.
This article dives into what OptionSet
is, how to use it, and examples of how it can simplify complex code involving sets of options.
What is OptionSet?
A protocol that allows you to define a set of unique, discrete options that can be combined efficiently using bitwise operations.
It is commonly used to represent configurations, permissions or status indicators where multiple values might be needed at once.
What Use OptionSet?
OptionSet
is potentially superiour to using multiple Bool
flags as it is likely to provide clean code that is easy to read, maintain and build features on.
OptionSet
is advantageous in scenarios where:
- There are multiple options that can apply simultaneously
- Managing multiple
Boolean
properties is too complex - Memory efficiency is important
Creating an OptionSet
struct TextStyleOptions: OptionSet {
let rawValue: Int
static let bold = TextStyleOptions(rawValue: 1 << 0)
static let italic = TextStyleOptions(rawValue: 1 << 1)
static let underline = TextStyleOptions(rawValue: 1 << 2)
static let strikethrough = TextStyleOptions(rawValue: 1 << 3)
}
Option sets all conform to RawRepresentable
by inheritance using the OptionSet
protocol. Whether using an option set or creating your own, you use the raw value of an option set instance to store the instance’s bitfield. The raw value must therefore be of a type that conforms to the FixedWidthInteger
protocol, such as UInt8
or Int
.
In this case rawValue
is an Int
.
.bold
has a rawValue
of 1 (binary 0001).
.italic
has a rawValue
of 2 (binary 0010).
.underline
has a rawValue
of 4 (binary 0100).