If you have read this previous post you have seen how to compare two enums with associated values for equality. The equality included the associated values as well which is only fair. But sometimes you are not interested in the associated values but only want to know, if the two enums are of the same case regardless of the possibly associated values; I call this in the following if they are „similar“.
OK, that should follow the same pattern we have used in the equality comparison. Let’s give it a try:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
enum Happiness3: Equatable { case Sad case Happy(ofGrade: Int) static func == (lhs: Happiness3, rhs: Happiness3) -> Bool { switch lhs { // look at the left hand side case .Sad: // its sad switch rhs { // and what's on the right? case .Sad: // also sad return true default: // something else break } case .Happy(let lgrade): // its happy with some grade switch rhs { // look on the right hand side case .Happy(let rgrade): // also happy return lgrade == rgrade // return true if grades are the same default: break } } return false // otherwise return false } func isSimilar(toHappiness rhs: Happiness3) -> Bool { switch self { // look at ourself case .Sad: // its sad switch rhs { // and what's on the right? case .Sad: // also sad return true default: // something else break } case .Happy(_): // its happy, grade is not interesting switch rhs { // look on the right hand side case .Happy(_): // also happy, grade is not interesting return true // return true regardless of grades default: break } } return false // otherwise return false } } |
This method uses the same nested switch blocks as the comparison method but ignores all associated values. Now we can write something like this:
1 2 3 4 |
mood3 = Happiness3.Happy(ofGrade: 5) if mood3.isSimilar(toHappiness: Happiness3.Happy(ofGrade: 0)) { Swift.print("3. Somewhat happy for the time being!") } |
OK, OK. There is also a shorter version of the function with a switch on both sides simultaneously:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
enum Happiness4: Equatable { case Sad case Happy(ofGrade: Int) static func == (lhs: Happiness4, rhs: Happiness4) -> Bool { switch (lhs, rhs) { // look at both sides simultaneously case (.Sad, .Sad): return true // both are sad // both happy: return true if grades are same case (.Happy(let lgrade), .Happy(let rgrade)): return lgrade == rgrade // for all other combinations: return false case (.Sad, _), (.Happy(_), _): return false } } func isSimilar(toHappiness rhs: Happiness4) -> Bool { switch (self, rhs) { // look at both sides simultaneously case (.Sad, .Sad): return true // both are sad // both happy: return true regardeless of grades case (.Happy(_), .Happy(_)): return true // for all other combinations: return false case (.Sad, _), (.Happy(_), _): return false } } } |
Cool, isn’t it? Here is the updated playground: