Understand and Create Custom OptionSet in Swift
In this article, we will learn what is
OptionSet in Swift and how to create your own custom
What is OptionSet?
- In Swift,
OptionSetis a protocol to represent bitset types, where individual bits represent members of a set.
OptionSetis similar to
enum, but they are designed to work as a set so we can use multiple values at the same time.
SetAlgebraprotocol, we can use methods like
isDisjointand several other methods that you might have used on
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
For example, to parse JSON string using
JSONSerialization we can provide
.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
structthat conforms to the
rawValueinstance property which must be of a type that conforms to the
FixedWidthIntegerprotocol — it’s normally,
- 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.
For now, we have learned what is
OptionSet and how to create our own
OptionSet. We saw that we can use
OptionSet for storing a finite list of options as a single value instead of an array.
Please feel free to comment below, if you have any questions.
If you like this article, feel free to share it with your friends and leave me a comment. Also, click on the 👏 clap button below to show how much you like the article.
Thanks for reading! 👨🏼💻
You can find me on:
Twitter | LinkedIn | GitHub | Medium | HackerRank | LeetCode | Stack Overflow