选项集合(OptionSet)与位移枚举

791 阅读1分钟

先说下简单使用

声明

struct CellTypeOptions: OptionSet {
    let rawValue: Int
    static let fuel = CellTypeOptions(rawValue: 1 << 0)
    static let trip = CellTypeOptions(rawValue: 1 << 1)
    static let detention = CellTypeOptions(rawValue: 1 << 2)
}

使用和判断

func testOptionSet() {
    var opt: CellTypeOptions = [.detention]
    opt = opt.union(.fuel)
    switch opt {
    case [.detention, .fuel]:
        print("two")
    case let opt where opt.contains([.detention]):
        print("test contain ")
    case [.fuel]:
        print("fuel")
    default:
        print("default ")
    }
}

feature

Swift使用struct来遵从OptionSet协议,以引入选项集合,而非enum。
和C一样,Swift中的选项集合结构体使用了高效的位域来表示,但是这个结构体本身表现为一个集合,它的成员则为被选择的选项。这允许你使用标准的集合运算来维护位域,比如使用contains(:)来检验集合中是否有某个成员,或者是用union(:)来组合两个位域,通过remove(_:)来移除某个成员。另外,由于OptionSet继承于ExpressibleByArrayLiteral,你可以使用数组字面量来生成一个选项集合。

常用方法:

/// add emement
func union(_ other: Self) -> Self
/// Returns a Boolean value that indicates whether a given element is a member of the option set.
func contains(_ member: Self) -> Bool
/// Removes the given element and all elements subsumed by it.
func remove(_ member: Self.Element) -> Self.Element?