> On May 17, 2016, at 7:24 PM, Brent Royal-Gordon <[email protected]> 
> 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


_______________________________________________
swift-users mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to