Search code examples
xcodemacosswiftuid

UID for swift objects


Is there any simple built-in way to generate unique idenitfiers for any in-app objects?(hash is not acceptable because it's ok in my situation to have objects with the same data) ID acceptable as either string or integer, only local uniqueness required. Google doesn't help


Solution

  • If all you need to do is determine if two objects that compare as equal with == are distinct, you can use the === operator:

    let first = MyObject(value: 1)
    let second = MyObject(value: 1)
    
    first == second // returns true
    first === second // returns false
    

    If you really want to get a unique identifier, spelunking into the Swift standard library reveals:

    /// Return an UnsafePointer to the storage used for `object`.  There's
    /// not much you can do with this other than use it to identify the
    /// object
    func unsafeAddressOf(object: AnyObject) -> UnsafePointer<Void>
    

    I make no claims as to the advisability of using that. It may not even work the way you think it will depending on copy-on-write shenanigans pulled by the compiler.