3

I want to compare the addresses of two Swift objects, like:

let a: AnyObject
let b: AnyObject

a < b

Of course this is not possible like this but I’m not able to find any way to achieve this.

I could just implement a C function to do this

bool compare(NSObject *a, NSObject *b){
    return a < b;
}

and then call it like

compare(a, b)

but this limits me to use NSObjects.

So my question is: Is there any way to achieve this purely in Swift?

idmean
  • 14,540
  • 9
  • 54
  • 83

2 Answers2

5

You can use the unsafeAddressOf function that returns an UnsafePointer value.

let elm0 = "hello world"
let elm1 = UIButton()

let address0 = unsafeAddressOf(elm0)
let address1 = unsafeAddressOf(elm1)

let compare = address0 > address1

Hope this helps.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
3

I found myself an answer.

There is a struct called ObjectIdentifier which can provide you a UIntValue to identify an object.

This UIntValue looks pretty much like it was the object reference, so I’ll use that:

class Person {
    var name: String

    init(name: String){
        self.name = name
    }
}

NSLog("%p", ObjectIdentifier(Person(name: "James")).uintValue)
NSLog("%p", ObjectIdentifier(Person(name: "Berta")).uintValue)
NSLog("%p", ObjectIdentifier(Person(name: "Charly")).uintValue)

Logs something similar to:

2015-08-29 15:04:21.567 App[10724:5283560] 0x7ff3a8415830
2015-08-29 15:04:21.568 App[10724:5283560] 0x7ff3a8643ba0
2015-08-29 15:04:21.568 App[10724:5283560] 0x7ff3a8415830
idmean
  • 14,540
  • 9
  • 54
  • 83