4

For example in EventKit there is a property on EKCalendar called supportedEventAvailabilities which is of type EKCalendarEventAvailabilityMask. It is a mask of all the supported event availabilities. I know you could theoretically set them like this (if this property was writable):

calendar.supportedEventAvailabilities = [.Busy, .Free]

But how do you read those values again? I ended up with code like this:

let availabilities = calendar.supportedEventAvailabilities
if (availabilities.rawValue & EKCalendarEventAvailabilityMask.Busy.rawValue) == EKCalendarEventAvailabilityMask.Busy.rawValue {
    // 'Busy' is in there!
}
if (availabilities.rawValue & EKCalendarEventAvailabilityMask.Free.rawValue) == EKCalendarEventAvailabilityMask.Free.rawValue {
    // 'Free' is in there!
}

But this does not feel right. Does anyone know how to do this properly?

Tom van Zummeren
  • 9,130
  • 12
  • 52
  • 63

1 Answers1

3

EKCalendarEventAvailabilityMask conforms to the new OptionSetType protocol which inherits from SetAlgebraType and offers a set-like interface. You can check for membership with

let availabilities = calendar.supportedEventAvailabilities
if availabilities.contains(.Busy) {
    // 'Busy' is in there!
}

or

if availabilities.isSupersetOf([.Busy, .Free]) {
    // Both .Busy and .Free are available ...
}

or

if availabilities.intersect([.Busy, .Free]) != [] {
    // At least one of .Busy and .Free is available ...
}

For more information, see protocol SetAlgebraType in the "Swift Standard Library Reference".

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Very cool. That's much cleaner than doing bitwise operations on the enum's raw values. Another trick I didn't know about. Was that added in Swift 1.2? – Duncan C Jun 27 '15 at 13:20