Created
October 19, 2017 17:49
-
-
Save cprovatas/8d4dafaa13da058da32b0f68f625b424 to your computer and use it in GitHub Desktop.
Solution to eliminate boilerplate code when Implementing Equatable for Associated Value Enums
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: ©, { 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