swiftprotocolsuniqueidentifierswift-extensions

Generating unique ids for each implementor of a protocol


I have the following I want to achieve in Swift:

I have a protocol

protocol IdProtocol {
  static var id: Int { get }
}

Now I want each implementor of this potocol to have a different value for id.

For example:

struct One: IdProtocol {}
struct Two: IdProtocol {}

Here, One will have id 0 and Two will have id 1 (or vice versa).

How can I implement this in Swift? I'd like to have this as a protocol extension so that all structs implementing IdProtocol will automatically be assigned an id. This can be done lazily.

I haven't been able to find a solution to this.


Solution

  • You won't be able to create it in this way that there is a consecutive Int, starting at 0 and incrementing for each type automatically. You would have to solve all kinds of issues in a manual way.

    What you could do however is the following: use a protocol extension to define a standard implementation for id and hash the name of the type:

    extension IdProtocol {
        static var id: Int {
            var hasher = Hasher()
            hasher.combine(String(describing: Self.self))
            return hasher.finalize()
        }
    }
    

    This should be enough for most cases. But it will be a (more or less) random Int for each type. Still, that id will stay constant between compiler runs (until you rename a class). And you should only run into collisions when the names collide as well.