Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Solution to eliminate boilerplate code when Implementing Equatable for Associated Value Enums
import UIKit
protocol AutoEquatableEnum {
static func == (lhs: Self, rhs: Self) -> Bool
}
extension AutoEquatableEnum {
static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.data == rhs.data
}
private var data: NSData {
var copy = self
return withUnsafePointer(to: &copy, { NSData(bytes: $0, length: MemoryLayout<Self>.size) })
}
}
enum Test: AutoEquatableEnum {
case foo(String)
case bar(String)
}
Test.foo("bar") == Test.foo("bar") // true
Test.foo("bar") == Test.bar("bar") // false
Test.bar("foo") == Test.bar("foo") // true
Test.bar("foo") == Test.bar("") // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment