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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With