Skip to content

Instantly share code, notes, and snippets.

@eMdOS
Created August 23, 2019 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eMdOS/62346e4c71f048e75187dd0806f8e89d to your computer and use it in GitHub Desktop.
Save eMdOS/62346e4c71f048e75187dd0806f8e89d to your computer and use it in GitHub Desktop.
Enum + Option -> Modern OptionSet
// 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