Skip to content

Instantly share code, notes, and snippets.

@cprovatas
Created October 19, 2017 17:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cprovatas/8d4dafaa13da058da32b0f68f625b424 to your computer and use it in GitHub Desktop.
Save cprovatas/8d4dafaa13da058da32b0f68f625b424 to your computer and use it in GitHub Desktop.
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