Last active
October 15, 2019 02:52
-
-
Save takasek/bd10fbc45f7886756d1c34f32fea4b7b to your computer and use it in GitHub Desktop.
「EntityはIDを持ってるよね」をprotocolで表現し、Entity.IDを定義不要にする
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
protocol Entity { | |
associatedtype RawIDValue: Hashable | |
typealias ID = EntityID<Self> | |
} | |
struct EntityID<E: Entity>: RawRepresentable, Hashable { | |
let rawValue: E.RawIDValue | |
} | |
extension EntityID { | |
init(_ value: E.RawIDValue) { | |
rawValue = value | |
} | |
} | |
struct Hoge: Entity, Equatable { | |
typealias RawIDValue = String | |
let id: ID | |
let name: String | |
} | |
let hogeID = Hoge.ID("id_a") | |
let hoge1 = Hoge(id: .init("id_a"), name: "田中") | |
let hoge2 = Hoge(id: .init("id_b"), name: "田中") | |
let hoge3 = Hoge(id: .init("id_b"), name: "鈴木") | |
print(hoge1.id == hogeID) // true | |
print(hoge1.id == hoge2.id) // false | |
print(hoge2.id == hoge3.id) // true | |
print(hoge2 == hoge3) // false | |
struct Fuga: Entity { | |
typealias RawIDValue = Int | |
let id: ID | |
} | |
struct Piyo: Entity { | |
typealias RawIDValue = Int | |
let id: ID | |
} | |
let fugaID = Fuga.ID(1) | |
let piyoID = Piyo.ID(1) | |
//print(fugaID == piyoID) | |
// 👆Error: Binary operator '==' cannot be applied to operands of type 'Fuga.ID' (aka 'EntityID<Fuga>') and 'Piyo.ID' (aka 'EntityID<Piyo>') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment