Lots of people know about switch cases with associated values, for example as follows:
enum Emoji { case lol(String) case ohnoes(String) case nothing }
Some code that uses the above enum:
let testcases: [Emoji] = [ .lol("🙂"), .ohnoes("😒"), .nothing ]
for testcase in testcases { switch testcase { case .lol(let emoji): print("Happy emoji: " + emoji) case .ohnoes(let emoji): print("Sad emoji: " + emoji) case .nothing: print("No emoji") } }
If however, you have common code that must run for both happy and sad emoji, it's possible to combine them into one case. However inside that case, you can still test for one specific case. The example below shows how you can print common code for both happy and sad emoji, but still detect happy emoji:
for testcase in testcases { switch testcase { case .lol(let emoji), .ohnoes(let emoji): if case .lol = testcase { print("Happy emoji detected: \(emoji)") } print("This is code that runs on any emoji") case .nothing: print("No emoji") } }