How to display OptionSet values in human-readable form?

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

    StrOptionSet Protocol:

    • Add a labels set property to test each label value on Self.

    StrOptionSet Extension:

    • Filter out which is not intersected.
    • Return the label text as array.
    • Joined with "," as CustomStringConvertible::description

    Here is the snippet:

    protocol StrOptionSet : OptionSet, CustomStringConvertible {
        typealias Label = (Self, String)
        static var labels: [Label] { get }
    }
    extension StrOptionSet {
        var strs: [String] { return Self.labels
                                    .filter{ (label: Label) in self.intersection(label.0).isEmpty == false }
                                    .map{    (label: Label) in label.1 }
        }
        public var description: String { return strs.joined(separator: ",") }
    }
    

    Add the label set for target option set VTDecodeInfoFlags.

    extension VTDecodeInfoFlags : StrOptionSet {
        static var labels: [Label] { return [
            (.asynchronous, "asynchronous"),
            (.frameDropped, "frameDropped"),
            (.imageBufferModifiable, "imageBufferModifiable")
        ]}
    }
    

    Use it

    let flags: VTDecodeInfoFlags = [.asynchronous, .frameDropped]
    print("flags:", flags) // output: flags: .asynchronous,frameDropped
    

提交回复
热议问题