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

Matthew Johnson matthew at anandabits.com
Tue May 17 21:28:26 CDT 2016


> On May 17, 2016, at 9:24 PM, Brent Royal-Gordon via swift-users <swift-users at swift.org> 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>?
>    }

Nice!

> 
> 
> -- 
> Brent Royal-Gordon
> Architechies
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



More information about the swift-users mailing list