How to display OptionSet values in human-readable form?

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

    struct MyOptionSet: OptionSet {
        let rawValue: UInt
        static let healthcare   = MyOptionSet(rawValue: 1 << 0)
        static let worldPeace   = MyOptionSet(rawValue: 1 << 1)
        static let fixClimate   = MyOptionSet(rawValue: 1 << 2)
        static let exploreSpace = MyOptionSet(rawValue: 1 << 3)
    }
    
    extension MyOptionSet: CustomStringConvertible {
        static var debugDescriptions: [(Self, String)] = [
            (.healthcare, "healthcare"),
            (.worldPeace, "world peace"),
            (.fixClimate, "fix the climate"),
            (.exploreSpace, "explore space")
        ]
    
        var description: String {
            let result: [String] = Self.debugDescriptions.filter { contains($0.0) }.map { $0.1 }
            return "MyOptionSet(rawValue: \(self.rawValue)) \(result)"
        }
    }
    

    Usage

    var myOptionSet: MyOptionSet = []
    myOptionSet.insert(.healthcare)
    print("here is my options: \(myOptionSet)")
    

提交回复
热议问题