Is there a way to test an OptionSet with a switch statement?

前端 未结 1 1952
暗喜
暗喜 2021-02-15 14:49

Defining a simple OptionSet:

public struct TestSet : OptionSet, Hashable
{
    public let rawValue: Int
    public init(rawValue:Int){ self.rawValue = rawValue}
         


        
1条回答
  •  灰色年华
    2021-02-15 15:34

    You can't do this directly because switch is using Equatable and, I think, is using SetAlgebra.

    However, you can wrap the OptionSet with something like:

    public struct TestSetEquatable: Equatable {
    
        let optionSet: T
    
        public static func == (lhs: Self, rhs: Self) -> Bool {
    
            return lhs.optionSet.isSuperset(of: rhs.optionSet)
        }
    }
    

    Which lets you do:

    let ostest : TestSet = [.A, .C]
    
    switch TestSetEquatable(optionSet: ostest) {
    
      case TestSetEquatable(optionSet: [.A, .B]):
       print("-AB")
       fallthrough
    
     case TestSetEquatable(optionSet: [.A, .C]):
       print("-AC")
       fallthrough
    
     case TestSetEquatable(optionSet: [.A]):
       print("-A")
       fallthrough
    
       default:
         print("-")
    }
    

    This prints:

    -AC
    -A
    - // from the fall through to default
    

    Opinion: I'm not inclined to do use this code myself but if I had to, this is what I would do.

    0 讨论(0)
提交回复
热议问题