So if you need a property which might have more than one enum case, you can use OptionSet.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.
