Shorter code with OptionSet in Swift

Tram Ho

If you want to know how to deal with Bitmasks in Swift or have you ever heard of OptionSet? This article will help you understand more about that

1. What is OptionSet?

Basically, OptionSet is a protocol, when confirm it we can work with bit mask . It is a representation for assigning each bit corresponding to an option. Let’s find out more.

2. How to implement OptionSet.

Here is a basic example of using OptionSet:

Now let’s explain the above code. The confirm OptionSet protocol requires a rawValue declaration, which is not necessarily of an Int type but of any type of FixedWidthInteger like Int8 or Int16. Next, you also need to declare static options. That’s all you need to do with OptionSet

You will probably wonder why you need to use static and << ?

Logically, options need to be declared static since you will access it directly without the relative initialization. Next, the option is declared as an instance of the struct with the assignment of rawValue to the binary code so the << operator is needed.

For example:

In the above example, we just converted the bits into 1 and 21

It is like:

So why using << might be more convenient to make sure you don’t break the rules of the binary counting formula (1,2,4,8,16, ..)

Why use OptionSet?

You can simply treat it as an option associated with a variable. Let’s see the example below:

For example:

Let’s see if we have an app that allows the user to choose their favorite pet. With that request, you will probably immediately think of enum .

and easy to use:

However, we already know that things change a lot, the application’s requirements have changed that the user can choose from many favorite pets. We will need to do this:

Now that seems plausible, but in some cases it doesn’t look very good. For example, what if this value needs to be sent to the server side? Will it be sent as a list?

Now let’s try using OptionSet to see the difference:

Note that multiplePets are of type Pet and not [Pet] . If you try to print rawValue you will see that singlePet is 2 ( 1<<1 ) and multiplePets is 3 ( 1<<1 + 1<<0 )

By following the method of using OptionSet, you can represent multiple options using only a single UInt8:

There is also an interesting feature of OptionSet is operation related operations for example:


OptionSet works based on bit masks, you can see it’s a good choice for storing a finite list of options as a single variable. However, please take note to use it wisely! and it is not a Collection

Reference source:

Share the news now

Source : Viblo