Created
September 4, 2017 18:34
-
-
Save aratkevich/7ec9860ca7c220f6b4532a8f96f8c8a1 to your computer and use it in GitHub Desktop.
Strongly typed identifiers
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
// Option 1 | |
protocol Identity { | |
associatedtype Identifier | |
var id: Identifier {get set} | |
} | |
struct Person: Identity { | |
typealias Identifier = String | |
var id: Identifier | |
var name: String | |
var age: Int? | |
} | |
func scrollToPerson(withId id: Person.Identifier) { | |
} | |
struct Building: Identity { | |
typealias Identifier = Int | |
var id: Identifier | |
var name: String | |
var age: Int? | |
} | |
func goToBuilding(id: Building.Identifier) { | |
} | |
// Option 2 | |
class Identifier: RawRepresentable, Hashable, Equatable { | |
let rawValue: String | |
init(rawValue: String) { self.rawValue = rawValue } | |
} | |
class PersonID: Identifier {} | |
struct Person { | |
let id: PersonID | |
var name: String | |
var age: Int? | |
} | |
class BuildingID: Identifier {} | |
struct Building { | |
let id: BuildingID | |
var title: String | |
var owner: Person | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment