Saik0s
7/13/2017 - 2:09 PM

Strongly Type Identifiers For Class Or Struct By Using Protocol and associated types

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) {
}