Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch to match multiple cases from OptionSetType

Tags:

swift

I have a struct Person extends OptionSetType. Later in code, How can I use a switch statement to check if an instance of Person is more than one value?

Thank you

struct Person: OptionSetType {
let rawValue: Int
init(rawValue: Int){
    self.rawValue = rawValue
}

    static let boy         = Person(rawValue: 1 << 0)
    static let young       = Person(rawValue: 1 << 1)
    static let smart       = Person(rawValue: 1 << 2)
    static let strong      = Person(rawValue: 1 << 3)
}

//later declared
var him: Person!

//later initialised
him = [.boy, .young]

//now test using a switch block
Switch (him) {
   case .boy & .young   // <----- How do you get this to work?

}

How would test for him == young and strong?
How to test him contains young and boy?

like image 518
Fred J. Avatar asked Dec 18 '15 14:12

Fred J.


1 Answers

OptionSetType is a subtype of SetAlgebraType, so you can use set algebra methods to test one combination of options against another. Depending on exactly what you want to ask (and what the sets in question are), there may be multiple ways to do it.

First, I'll put the attributes I'm querying for in a local constant:

let youngBoy: Person = [.Young, .Boy] 

Now, to use that for one kind of test that works well:

if him.isSupersetOf(youngBoy) {
    // go to Toshi station, pick up power converters
}

Of course, what this is specifically asking is whether him contains all the options listed in youngBoy. That might be all you care about, so that's just fine. And it's also safe if you later extend Person to have other options, too.

But what if Person had other possible options, and you wanted to assert that him contains exactly the options listed in youngBoy, and no others? SetAlgebraType extends Equatable, so you can just test with ==:

if him == youngBoy {
    // he'd better have those units on the south ridge repaired by midday
}

By the way, you don't want to use a switch statement for this. Switch is for selecting one out of several possible cases (is it A or B?), so using it to test combinatorics (is it A, B, A and B, or neither?) makes your code unwieldy.

like image 181
rickster Avatar answered Oct 14 '22 03:10

rickster