Created
August 23, 2019 21:10
-
-
Save eMdOS/62346e4c71f048e75187dd0806f8e89d to your computer and use it in GitHub Desktop.
Enum + Option -> Modern OptionSet
This file contains 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
// Playground | |
protocol Option: RawRepresentable, Hashable, CaseIterable {} | |
extension Set where Element: Option { | |
var rawValue: Int { | |
var rawValue = 0 | |
for (index, element) in Element.allCases.enumerated() where contains(element) { | |
rawValue |= (1 << index) | |
} | |
return rawValue | |
} | |
} | |
// MARK: - Example | |
enum Topping: String, Option { | |
case pepperoni, onions, bacon, extraCheese, greenPeppers, pineapple | |
} | |
typealias Toppings = Set<Topping> | |
struct Pizza { | |
let toppings: Toppings | |
} | |
let pizza = Pizza(toppings: [.bacon, .onions, .pepperoni]) | |
print("Pizza:", pizza) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment