The Pragmatic Ball boy

iOSを中心にやってる万年球拾いの老害エンジニアメモ

Swift2でのbitmask

Swift2からRawOptionSetTypeがOptionSetType (OptionSetType Protocol Reference) に変わったため、

例えばUIViewAutoresizingの場合、 これまでは

view?.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight

だったのが

self.view?.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]

になります。

OptionSetTypeのprotocol extensionでいくつかメソッドが用意されているので、これらを使って、and, or, exclusive orなどのbit演算を行ったり、containsを使ってbitが立っているかチェックできます

extension OptionSetType {

    /// Returns the set of elements contained in `self`, in `other`, or in
    /// both `self` and `other`.
    func union(other: Self) -> Self

    /// Returns the set of elements contained in both `self` and `other`.
    func intersect(other: Self) -> Self

    /// Returns the set of elements contained in `self` or in `other`,
    /// but not in both `self` and `other`.
    func exclusiveOr(other: Self) -> Self
}

extension OptionSetType where Element == Self {

    /// Returns `true` if `self` contains `member`.
    ///
    /// - Equivalent to `self.intersect([member]) == [member]`
    func contains(member: Self) -> Bool

    /// If `member` is not already contained in `self`, insert it.
    ///
    /// - Equivalent to `self.unionInPlace([member])`
    /// - Postcondition: `self.contains(member)`
    mutating func insert(member: Self)

    /// If `member` is contained in `self`, remove and return it.
    /// Otherwise, return `nil`.
    ///
    /// - Postcondition: `self.intersect([member]).isEmpty`
    mutating func remove(member: Self) -> Self?
}