Skip to content

Instantly share code, notes, and snippets.

@wata
Created April 7, 2020 04:27
Show Gist options
  • Save wata/eb3f9a287cfc323843025fedccfa4c26 to your computer and use it in GitHub Desktop.
Save wata/eb3f9a287cfc323843025fedccfa4c26 to your computer and use it in GitHub Desktop.
An OptionSet suitable for debugging
protocol DebuggableOptionSet: OptionSet, CustomDebugStringConvertible {
static var allOptions: [Self] { get }
static var allOptionNames: [String] { get }
}
extension DebuggableOptionSet where Self == Self.Element {
var debugDescription: String {
var result = ""
for (index, element) in Self.allOptions.enumerated() {
if contains(element) {
let name = Self.allOptionNames[index] + "(\(element.rawValue))"
result += result.isEmpty ? "\(name)": ", \(name)"
}
}
return String(describing: type(of: self)) + "[\(result)]"
}
}
@wata
Copy link
Author

wata commented Apr 7, 2020

Usage

    struct ShippingOptions: DebuggableOptionSet {
        let rawValue: Int

        static let nextDay    = ShippingOptions(rawValue: 1 << 0)
        static let secondDay  = ShippingOptions(rawValue: 1 << 1)
        static let priority   = ShippingOptions(rawValue: 1 << 2)
        static let standard   = ShippingOptions(rawValue: 1 << 3)

        static let allOptions: [ShippingOptions] = [.nextDay, .secondDay, .priority, .standard]
        static let allOptionNames: [String] = ["nextDay", "secondDay", "priority", "standard"]
    }
let options: ShippingOptions = [.priority]
print(options)
// Prints "ShippingOptions[priority(1)]"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment