[swift-users] Reducing the boilerplate for my ID types

Ray Fix rayfix at gmail.com
Tue May 17 21:47:11 CDT 2016


> On May 17, 2016, at 7:24 PM, Brent Royal-Gordon <brent at architechies.com> wrote:
> 
>> I have some ID types that are simple ints coming back from a database.  I wanted to improve type safety so I don’t accidentally assign product IDs to user IDs, etc.  I want to be able to print it and use it as a dictionary key.  So it is a trivial wrapper of Int.  E.g.
>> 
>> struct CustomerID: Hashable, CustomStringConvertible {
>>    init(_ value: Int) { self.value = value }
>>    let value: Int
>>    var hashValue: Int { return value.hashValue }
>>    var description: String { return String(value) }
>> }
>> 
>> func ==(lhs: CustomerID, rhs: CustomerID) -> Bool {
>>    return lhs.value == rhs.value
>> }
> 
> Rather than going the protocol route, how about a generic type?
> 
>    struct ID<IdentifiableType: Identifiable>: Hashable, CustomStringConvertible {
>        init(_ value: Int) { self.value = value }
>        let value: Int
>        var hashValue: Int { return value.hashValue }
>        var description: String { return String(value) }
>    }
> 
>    func ==<T: Identifiable>(lhs: ID<T>, rhs: ID<T>) -> Bool {
>        return lhs.value == rhs.value
>    }
> 
>    protocol Identifiable {
>        var id: ID<Self>? { get }
>    }
> 
>    struct Customer: Identifiable {
>        var id: ID<Customer>?
>    }
> 

Very cool!  Thank you.

Notes to self: 

ID uses the Identifiable model as sort of a phantom type.  Given my current code base, it also convenient for me to do

typealias CustomerID = ID<Customer>

Being able to define new ID types in one line like this is exactly the solution I was looking for.

Ray




More information about the swift-users mailing list