我有一个结构Person扩展OptionSetType。稍后在代码中,如何使用switch语句检查Person的实例是否多于一个值?
谢谢
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?
}
如何测试他==年轻而强壮?
如何测试他包含年轻人和男孩?
答案 0 :(得分:5)
OptionSetType
是SetAlgebraType
的子类型,因此您可以使用set algebra方法来测试一个选项组合与另一个组合。根据您想要问的具体内容(以及所讨论的内容集),可能有多种方法可以实现。
首先,我将我查询的属性放在一个本地常量中:
let youngBoy: Person = [.Young, .Boy]
现在,将其用于一种效果良好的测试:
if him.isSupersetOf(youngBoy) {
// go to Toshi station, pick up power converters
}
当然,具体问的是him
是否包含youngBoy
中列出的所有选项。这可能就是你所关心的,所以这很好。如果您稍后将Person
扩展为其他选项,那也是安全的。
但是,如果Person
有其他可能的选项,并且您想断言him
包含 youngBoy
中列出的选项,而不是其他选项,该怎么办? SetAlgebraType
扩展了Equatable
,因此您只需使用==
进行测试:
if him == youngBoy {
// he'd better have those units on the south ridge repaired by midday
}
顺便说一句,您不想为此使用switch
语句。 Switch用于从几种可能的情况中选择一种(是A还是B?),所以用它来测试组合(是A,B,A和B,还是两者都没有?)会使你的代码变得笨拙。
答案 1 :(得分:0)
只是简单的案例:
switch him {
case [.boy, .young]:
// code
default:
break
}