Swift中 使用位移枚举

以下内容 摘自 http://www.bjbkws.com/apply/1233/   亲测好用 解决了我的问题    

 

struct MyOptions : RawOptionSet {

        var value: UInt = 0

        init(_ value: UInt) { self.value = value }

        func toRaw() -> UInt { return self.value }

        func getLogicValue() -> Bool { return self.value != 0 }

        static func fromRaw(raw: UInt) -> MyOptions? { return MyOptions(raw) }

        static func fromMask(raw: UInt) -> MyOptions { return MyOptions(raw) }

        

        static var None: MyOptions          { return MyOptions(0) }

        static var FirstOption: MyOptions   { return MyOptions(1 << 0) }

        static var SecondOption: MyOptions  { return MyOptions(1 << 1) }

        static var ThirdOption: MyOptions   { return MyOptions(1 << 2) }

    }

    

    func == (lhs: MyOptions, rhs: MyOptions) -> Bool     { return lhs.value == rhs.value }

    func | (lhs: MyOptions, rhs: MyOptions) -> MyOptions { return MyOptions(lhs.value | rhs.value) }

    func & (lhs: MyOptions, rhs: MyOptions) -> MyOptions { return MyOptions(lhs.value & rhs.value) }

    func ^ (lhs: MyOptions, rhs: MyOptions) -> MyOptions { return MyOptions(lhs.value ^ rhs.value) }

    更或者你也可以

    class MyOptions {

        class var None   : UInt32 { return 0 }

        class var All    : UInt32 { return UInt32.max }

        class var First  : UInt32 { return 1 }

        class var Second : UInt32 { return 1<<1 }

        class var Third  : UInt32 { return 1<<2 }

    }

    范例用法

    physicsBody.categoryBitMask = MyOptions.First 

    physcisBody.collisionBitMask = MyOptions.First | MyOptions.Second

posted @ 2015-06-29 23:10  风中一场梦  阅读(1132)  评论(0编辑  收藏  举报