Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.