Category

Swift 2 OptionSetType

Swift Language

Swift 2 OptionSetType

Swift 2/iOS 9 broke my calendar/date code.
What’s going on?

Introduction

Table of Contents

If you have an app that does anything with dates, you most likely have code someplace like this.
You get the date’s components, do something with them, and construct a new date from those components.

Broken in iOS 9.
So, the first thought I had was “Did they change the damn names again?” (MonthCalendarUnit for example was previously renamed CalendarUnitMonth).
No, that’s not it. Sort of.

What they did away with was that bitwise or-ing of components.

You do this now to specify the components.

So, MonthCalendarUnit -> CalendarUnitMonth -> Month?
There’s a “bit” more to it.

RawOptionSetType

Table of Contents

The “old” NSCalendarUnit is a RawOptionSetType.
Here is an example definition of options for a hoagie (not a sub – in spite of what The Google says – which are inferior. Hey, the name even implies “sub”standard!).

There’s some boilerplate setup funcs because of the inheritance thing, and then the individual options are defined by bit shifting 1 to create a bitmask.

This is how you would use these options. To set an option, you bitwise-or them into a variable.

You can see if an option is set by doing a bitwise-and like this.

Just like everywhere else you deal with bits. Or to set, And to get, Shift to create masks.

OptionSetType

Table of Contents

The new! and improved! way in Swift 2 is to use OptionSetType instead of RawOptionSetType.
No bits, just values. You can even define “aggregate” options like “TheWorks” in this example.

And then to use them in our domain struct:

As you see, OptionSetType provides several funcs for operating on the options.
Is this easier than dealing with bits?
Well, I still use The Emacs, so I’m the wrong guy to ask.

Some Other examples

Table of Contents

Here are a few more places you might find these new option sets.

UIViewAutoresizing is an OptionSetType.

UIUserNotificationType is an OptionSetType.

You will find many more examples and you try to run your old pre 2.0 code.

Summary

Table of Contents

OptionSetType has replaced RawOptionSetType.
You don’t have to deal with bit level operations now.
At least, not for options.

Resources

Table of Contents

Github repository

OptionSetType documentation

SetAlgebraType protocol

Do you want a really good hoagie?
Amato Brothers Deli
They aren’t paying me for this plug. I just eat there all the time.

One Reply to “Swift 2 OptionSetType”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.