Created
June 27, 2016 11:37
-
-
Save sinsoku/d9911f37bf8b950ecd3a6a865c0e0f4a to your computer and use it in GitHub Desktop.
Equatable の振る舞いを Generics で変えたい
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
| struct A<T>: Equatable { | |
| let name: String | |
| // 2. 最悪、Tに比較メソッドを実装する | |
| // func == <T>(lhs: A<T>, rhs: A<T>) -> Bool { | |
| // return T.compare(lhs, rhs) | |
| // } | |
| } | |
| func == <T>(lhs: A<T>, rhs: A<T>) -> Bool { | |
| return false | |
| } | |
| protocol P {} | |
| protocol Q {} | |
| func == <T : P>(lhs: A<T>, rhs: A<T>) -> Bool { | |
| return true | |
| } | |
| // 1. プロトコルで Equatable の挙動を変えたい | |
| let a1 = A<P>(name: "name") | |
| let b1 = A<P>(name: "name") | |
| let r1 = a1 == b1 | |
| print(r1) // true にしたいけど、 false | |
| let a2 = A<Q>(name: "name") | |
| let b2 = A<Q>(name: "name") | |
| let r2 = a2 == b2 | |
| print(r2) | |
| // 3. 理想は Generics のデフォルトも使いたい | |
| /* | |
| let a0 = A(name: "name") | |
| let b0 = A(name: "name") | |
| let r0 = a == b | |
| print(r0) | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment