You cannot do this directly because switch uses Equatable and, I think, uses SetAlgebra.
However, you can wrap something like this in OptionSet:
public struct TestSetEquatable<T: OptionSet>: Equatable {
let optionSet: T
public static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.optionSet.isSuperset(of: rhs.optionSet)
}
}
What allows you to 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 am not inclined to use this code myself, but if I had to, this is what I would do.
source
share