Swift OptionSet

So if you need a property which might have more than one enum case, you can use OptionSet.

struct CakeIngredients: OptionSet {
static let banana = CakeIngredients(rawValue: 1 << 0)
static let strawberry = CakeIngredients(rawValue: 1 << 1)
static let apple = CakeIngredients(rawValue: 1 << 2)
let rawValue: Int
init(rawValue: Int) {
self.rawValue = rawValue
}
}
let cake1: CakeIngredients = []
let cake2: CakeIngredients = [.banana]
let cake3: CakeIngredients = [.banana, .strawberry]
let cake4: CakeIngredients = [.banana, .strawberry, .apple]

Bitwise shift operator is used to take advantage of OptionSet features such as intersection and union:

print(cake2.intersection(cake3)) //CakeIngredients(rawValue: 1) => banana
print(cake2.union(cake3)) //CakeIngredients(rawValue: 3) => banana, strawberry

CakeIngredients(rawValue: 3) means banana and strawberry because rawValue of banana is 1 and rawValue of strawberry is 2 and sum is 3.

Leave a comment