-
-
Save Saik0s/04da532c56116f1cca11ea88594c1a28 to your computer and use it in GitHub Desktop.
Strongly Type Identifiers For Class Or Struct By Using Protocol and associated types
This file contains hidden or 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
| /* | |
| 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