Best way to compare two any type values in swift

683 views Asked by At

I have a class which has property value of type Any I have implemented a didSet method for the value like this

didSet {
  if oldValue == nil && self.value != nil {
    // do something
  }
  else {
    if let val = self.value as? AnyHashable, let oldVal = oldValue as? AnyHashable {
      if val != oldVal {
        // do something 
      }
    }
  }
}

My value is optional type so I want to verify the nil case too. Is there are better way of doing that I do not want to cast to Anyhashasble I want them to be casted to the class they belong.

1

There are 1 answers

0
SIlvester On

Well, if you assume that this property is aways, and if only always, a reference type, then you can try to use AnyObject instead of Any and use === operator to check if pointers are pointing to same object.

Something like this:

class Test {

    var object: AnyObject? {
        didSet {
            if oldValue === object {
                debugPrint("Old object")
            } else {
                debugPrint("New object")
            }
        }
    }
}

class SomeClass {}

let test = Test()
let s = SomeClass()

test.object = s
test.object = s
test.object = SomeClass()

The result will be:

"New object" - because previous value was nil

"Old object" - because we assigned same s

"New object" - because we assigned completely new object