Switch statement for imported NS_OPTIONS (RawOptionSetType) in Swift?

后端 未结 4 1690
既然无缘
既然无缘 2021-01-21 12:26

The switch statement in Swift is so much more expressive. I\'m wondering if this might be possible:

Lets look at UIViewAutoresizing for example. It\'s defined in Objecti

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-21 13:19

    I was frustrated enough about this problem that I wrote a Bitmask class that can handle these use cases. The code is up on Github: brynbellomy/SwiftBitmask

    It allows you to do stuff like this with any kind of object as your underlying type (here I'm using an enum):

    enum MonsterAttributes : IBitmaskRepresentable, IAutoBitmaskable {
        case Big, Ugly, Scary
    
        static var autoBitmaskValues : [MonsterAttributes] = [.Big, .Ugly, .Scary,]
        var  bitmaskValue: UInt16  { return AutoBitmask..autoBitmaskValueFor(self) }
        init(bitmaskValue: UInt16) { self = AutoBitmask.autoValueFromBitmask(bitmaskValue) }
    }
    
    // various ways to initialize
    let option : MonsterAttributes = .Ugly
    
    let bitmaskOfOption        = Bitmask(option)
    let anotherBitmaskOfOption = |MonsterAttributes.Ugly // same as bitmaskOfOption
    
    let orWithVar = option | .Big                 // == Bitmask with a bitmaskValue of 1 | 2
    let simpleOr  = MonsterAttributes.Big | .Ugly // == Bitmask with a bitmaskValue of 1 | 2
    
    // getting the raw integral bitmask value
    let simpleOrValue = simpleOr.bitmaskValue                        // == UInt16(1 | 2)
    let orValue       = (MonsterAttributes.Big | .Ugly).bitmaskValue // == UInt16(1 | 2)
    
    // implements BooleanType
    if simpleOr & .Ugly             { /* this code will execute */ }
    
    // supports pattern matching operator
    if simpleOr ~= .Ugly            { /* this code will execute */ }
    if simpleOr ~= (.Ugly | .Scary) { /* this code will execute */ }
    

    ... and all you have to do is implement a one-property protocol.

    I'm really curious if anyone has any feedback on or ideas for the code, so please leave an issue in the queue if you think of anything!

提交回复
热议问题