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

Brent Royal-Gordon brent at architechies.com
Tue May 17 21:24:58 CDT 2016


> 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>?
    }


-- 
Brent Royal-Gordon
Architechies



More information about the swift-users mailing list