How to display OptionSet values in human-readable form?

后端 未结 5 1469
别跟我提以往
别跟我提以往 2021-02-13 21:17

Swift has the OptionSet type, which basically adds set operations to C-Style bit flags. Apple is using them pretty extensively in their frameworks. Examples include the options

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-13 21:21

    This is how I did it.

    public struct Toppings: OptionSet {
            public let rawValue: Int
            
            public static let cheese = Toppings(rawValue: 1 << 0)
            public static let onion = Toppings(rawValue: 1 << 1)
            public static let lettuce = Toppings(rawValue: 1 << 2)
            public static let pickles = Toppings(rawValue: 1 << 3)
            public static let tomatoes = Toppings(rawValue: 1 << 4)
            
            public init(rawValue: Int) {
                self.rawValue = rawValue
            }
        }
        
        extension Toppings: CustomStringConvertible {
            
            static public var debugDescriptions: [(Self, String)] = [
                (.cheese, "cheese"),
                (.onion, "onion"),
                (.lettuce, "lettuce"),
                (.pickles, "pickles"),
                (.tomatoes, "tomatoes")
            ]
            
            public var description: String {
                let result: [String] = Self.debugDescriptions.filter { contains($0.0) }.map { $0.1 }
                let printable = result.joined(separator: ", ")
                
                return "\(printable)"
            }
        }
    

提交回复
热议问题