切换多个枚举



上下文是我有一个协议,它涵盖了我想要做的非常一般的情况。然后我使另外两个子协议符合它。

protocol MasterProtocol {}
protocol ChildProtocol1: MasterProtocol {}
protocol ChildProtocol2: MasterProtocol {}
class Thing1: ChildProtocol1 {}
class Thing2: ChildProtocol1 {}
class Thing3: ChildProtocol2 {}
class Thing4: ChildProtocol2 {}

现在我有了一个像这样的enum设置

enum Protocol1Classes {
case thing1
case thing2
}
enum Protocol2Classes {
case thing3
case thing4
}

现在我有两个非常密切相关的枚举它们的组合情况涵盖了所有符合MasterProtocol的类我想切换它们的组合值

func doThing(value: (Protocol1Classes || Protocol2Classes)) {
switch value {
case .thing1:
// Do Master Protocol Stuff to Thing1
case .thing2:
// Do Master Protocol Stuff to Thing2
case .thing3:
// Do Master Protocol Stuff to Thing3
case .thing4:
// Do Master Protocol Stuff to Thing4  
}
}

显然这行不通。有办法得到这样的东西吗?不需要声明第三个枚举,它只是组合了两个枚举中的情况?

感谢

您可以通过为两个枚举实现相同的函数来轻松解决这个问题,然后编译器将知道使用哪个。

func doThing(value: Protocol1Classes) {
switch value {
case .thing1:
print("do stuff 1")
case .thing2:
print("do stuff 2")
}
}
func doThing(value: Protocol2Classes) {
switch value {
case .thing3:
print("do stuff 3")
case .thing4:
print("do stuff 4")
}
}

那么调用它们就很简单了

doThing(value: .thing1)
doThing(value: .thing2)
doThing(value: .thing3)
doThing(value: .thing4)

做事情1
做事情2
做事情3
做事情4

最新更新