Last active
July 5, 2023 09:21
-
-
Save bonoogi/f98fb6eba5f61fbc771feebdfb45ad27 to your computer and use it in GitHub Desktop.
Equatable 구현에 도움을 주기 위한 프로퍼티 래퍼
This file contains hidden or 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
| @propertyWrapper struct IgnoreEquatable<Value>: Equatable { | |
| var wrappedValue: Value | |
| static func == (lhs: IgnoreEquatable<Value>, rhs: IgnoreEquatable<Value>) -> Bool { | |
| true | |
| } | |
| } | |
| @propertyWrapper struct CustomEquatable<Value>: Equatable { | |
| var wrappedValue: Value | |
| var isEqual: (Value, Value) -> Bool | |
| static func == (lhs: CustomEquatable<Value>, rhs: CustomEquatable<Value>) -> Bool { | |
| lhs.isEqual(lhs.wrappedValue, rhs.wrappedValue) | |
| } | |
| } | |
| let stringAnyDictEquatable: ([String: Any], [String: Any]) -> Bool = { | |
| return NSDictionary(dictionary: $0).isEqual(to: $1) | |
| } | |
| struct Foo: Equatable { | |
| @CustomEquatable(isEqual: stringAnyDictEquatable) var delegated: [String: Any] = [:] | |
| @IgnoreEquatable var ignored: Int | |
| } | |
| let foo1 = Foo(delegated: ["123": 123, "321": true], ignored: 2) | |
| let foo2 = Foo(delegated: ["123": 123, "321": true], ignored: 3) | |
| let foo3 = Foo(delegated: ["12": 123, "321": true], ignored: 3) | |
| print(foo1 == foo2) // true | |
| print(foo1 == foo3) // false | |
| // foo1.ignored: 2, foo2.ignored: 3, foo1.ignored == foo2.ignored: false | |
| print("foo1.ignored: \(foo1.ignored), foo2.ignored: \(foo2.ignored), foo1.ignored == foo2.ignored: \(foo1.ignored == foo2.ignored)") | |
| // 실제 delegated 값은 Equatable을 준수하지 않기 때문에 빌드 오류가 남 | |
| print(foo1.delegated == foo2.delegated) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment