Understand and Create Custom OptionSet in Swift
Step by step guide for creating custom OptionSet
In this article, we will learn what is OptionSet
in Swift and how to create your own custom OptionSet
.
What is OptionSet?
- In Swift,
OptionSet
is a protocol to represent bitset types, where individual bits represent members of a set. OptionSet
is similar toenum
, but they are designed to work as a set so we can use multiple values at the same time.- As
OptionSet
confirms toSetAlgebra
protocol, we can use methods likeintersection
,union
,contains
,isDisjoint
, and several other methods that you might have used onSet
.
As a matter of fact, Swift’s OptionSet protocol is the bridged version of Objective-C's NS_OPTIONS enum.
According to the documentation, there are over 300 types in Apple SDKs that conform to OptionSet
For example, to parse JSON string using JSONSerialization
we can provide .prettyPrinted
and .sortedKeys
as options for the final JSON.
Creating a custom OptionSet type:
Creating our own custom OptionSet
is very straightforward. To do this,
Declare a new struct that conforms to the
OptionSet
protocol.Define
rawValue
instance property which must be of a type that conforms to theFixedWidthInteger
protocol — it’s normally,Int
orUInt8
.Next, create static instances of your struct for all options, where each option should have unique raw value that’s a power of two (1, 2, 4, 8, and so forth) — It’s common to use bit-shifting
(<<)
operator to avoid mistakes.Add one or more of those instances as new statics.
To demonstrate this, let’s create a UserAccess struct that defines different level of access of the users like read, write, modify, etc.
All those options need unique raw values, so we’re going to use left bit shifting — 1 << 0
, 1 << 1
, and so on to avoid mistakes. We can also specify named aliases for specific combinations of values.
Here’s how it looks in Swift:
NOTE: In the above example, we have used UInt8 which uses 8 bits for its storage. Hence we can define max 8 unique options. You may use UInt16 in case you have more options.
Using an OptionSet type:
- To create an instance of an option set, assign one of the type’s static members to your variable.
- To create an instance of multiple option set, assign an array literal with multiple static members of the type’s.
- To create an empty instance, assign an empty array literal
([])
to your variable.
Summary:
For now, we have learned what is OptionSet
and how to create our own OptionSet
. We also see that we can use OptionSet
for storing a finite list of options as a single value instead of an array.
References:
- https://developer.apple.com/documentation/swift/optionset
- https://swiftdoc.org/v5.1/protocol/optionset/
You can find me on:
Twitter | Tooter | LinkedIn | GitHub | Medium | HackerRank | LeetCode | Stack Overflow