Skip to content

Instantly share code, notes, and snippets.

@takasek
Last active October 15, 2019 02:52
Show Gist options
  • Save takasek/bd10fbc45f7886756d1c34f32fea4b7b to your computer and use it in GitHub Desktop.
Save takasek/bd10fbc45f7886756d1c34f32fea4b7b to your computer and use it in GitHub Desktop.
「EntityはIDを持ってるよね」をprotocolで表現し、Entity.IDを定義不要にする
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