Skip to content

Instantly share code, notes, and snippets.

@juliengdt
Last active September 21, 2019 15:55
Show Gist options
  • Save juliengdt/fd5bbeccb5246cab1d615b686e9470d5 to your computer and use it in GitHub Desktop.
Save juliengdt/fd5bbeccb5246cab1d615b686e9470d5 to your computer and use it in GitHub Desktop.
Strongly Type Identifiers For Class Or Struct By Using Protocol and associated types
/*
In response of Tom Lokhort's article.
A third alternative: alternative 2 under steroïds
---
Source: http://tom.lokhorst.eu/2017/07/strongly-typed-identifiers-in-swift
*/
struct GenericIdentifier<T>: RawRepresentable, Hashable, Equatable {
let rawValue: String
init(rawValue: String) { self.rawValue = rawValue }
}
/*
Usage for both struct and class types, a bit lighter than "alternative 2"
*/
protocol Identifiable {
associatedtype IdentifiableType
typealias Identifier = GenericIdentifier<IdentifiableType>
}
struct Person: Identifiable {
typealias IdentifiableType = Person
let id: Identifier
var name: String
var age: Int?
}
/*
Usage for class type only, lighter than "alternative 2"
*/
protocol Identifiable: class {
typealias Identifier = GenericIdentifier<Self>
}
class Person: Identifiable {
let id: Identifier
var name: String
var age: Int?
init() {
self.id = Identifier(rawValue: "")
self.name = "toto"
}
}
// The same on calls
func scrollToPerson(withId id: Person.Identifier) {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment