How to display OptionSet values in human-readable form?

后端 未结 5 1495
别跟我提以往
别跟我提以往 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:33

    Here is one approach I've taken, using a dictionary and iterating over the keys. Not great, but it works.

    struct MyOptionSet: OptionSet, Hashable, CustomStringConvertible {
    
        let rawValue: Int
        static let zero = MyOptionSet(rawValue: 1 << 0)
        static let one = MyOptionSet(rawValue: 1 << 1)
        static let two = MyOptionSet(rawValue: 1 << 2)
        static let three = MyOptionSet(rawValue: 1 << 3)
    
        var hashValue: Int {
            return self.rawValue
        }
    
        static var debugDescriptions: [MyOptionSet:String] = {
            var descriptions = [MyOptionSet:String]()
            descriptions[.zero] = "zero"
            descriptions[.one] = "one"
            descriptions[.two] = "two"
            descriptions[.three] = "three"
            return descriptions
        }()
    
        public var description: String {
            var result = [String]()
            for key in MyOptionSet.debugDescriptions.keys {
                guard self.contains(key),
                    let description = MyOptionSet.debugDescriptions[key]
                    else { continue }
                result.append(description)
            }
            return "MyOptionSet(rawValue: \(self.rawValue)) \(result)"
        }
    
    }
    
    let myOptionSet = MyOptionSet([.zero, .one, .two])
    
    // prints MyOptionSet(rawValue: 7) ["two", "one", "zero"]
    

提交回复
热议问题