Unit flags in Swift, NSCalendar date components example

In Objective-C, when we want to pass unit flags, we could create a bitmask of the different options, like the commented code below shows:

Things work very differently in Swift, which might be a bit confusing.

This is because in Swift, NSCalendarUnit is a struct of type OptionSetType.

Understanding these differences in Foundation is a great way to grasp the way Swift works, and how it translates from Objective-C. For example, if you wanted to learn more about this, jump by using CMD + SHIFT + O, type NSCalendar.h, and hit Enter. You’ll see the NSCalendar header file. Now, if you want to see the Swift interface, select Navigate > Jump to Generated Interface.

This is just a small piece of the puzzle, to understand NSDateComponents in more detail, see Mattt’s article here.