Skip to content

Instantly share code, notes, and snippets.

@aratkevich
Created September 4, 2017 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aratkevich/7ec9860ca7c220f6b4532a8f96f8c8a1 to your computer and use it in GitHub Desktop.
Save aratkevich/7ec9860ca7c220f6b4532a8f96f8c8a1 to your computer and use it in GitHub Desktop.
Strongly typed identifiers
// 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