The context for this is that I have a protocol which covers a very general case of what I want to do. And then I conform two other sub-protocols to it.
protocol MasterProtocol {}
protocol ChildProtocol1: MasterProtocol {}
protocol ChildProtocol2: MasterProtocol {}
class Thing1: ChildProtocol1 {}
class Thing2: ChildProtocol1 {}
class Thing3: ChildProtocol2 {}
class Thing4: ChildProtocol2 {}
Now I have an enum setup like this
enum Protocol1Classes {
case thing1
case thing2
}
enum Protocol2Classes {
case thing3
case thing4
}
Now I have two very closely related enums where the combined cases cover all the classes that conform to the MasterProtocol and I want to switch over their combined values
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
}
}
Clearly this wont work. Is there a way to get something like this? Without having to declare a third enum which just combines the cases in the two enums?
Thanks
You can easily solve this by implementing the same function for both enums and then the compiler will know which one to use.
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")
}
}
Then calling them will be simple
doThing(value: .thing1)
doThing(value: .thing2)
doThing(value: .thing3)
doThing(value: .thing4)
do stuff 1
do stuff 2
do stuff 3
do stuff 4