Comparing two custom objects in swift

I have the following protocol defined in Swift:

protocol RecordingObserver {
    func aFunc()
}

      

Somewhere I need to compare two objects that implement this protocol to check if they are the same. The problem I'm having is that apparently Swift doesn't allow us to do this:

func areEqual(a:RecordingObserver,b:RecordingObserver){
    if a === b {
        println("Equal")
    }
}

      

Any idea why this is happening? And how can I do it differently?

+3


source to share


4 answers


===

is identical to the operator and is used to check if references to two objects refer to the same object instance. It can only be applied to reference types (i.e. instances of a class

).

===

differs from the "equal" operator ==

(which is required in the protocol Equatable

).

Therefore, considering that

  • actual observers are instances class

    and
  • Your purpose - to check whether your tags are a

    and b

    in one instance,

you need to define the protocol as a class protocol:



protocol RecordingObserver : class {
    // ...
}

      

Then

func areEqual(a:RecordingObserver,b:RecordingObserver){
    if a === b {
        println("a and b refer to the same object instance")
    }
}

      

compiles (and runs as expected), because the compiler knows that a

and b

are reference types.

+4


source


Your class must support Equatable protocol in order to use ==

https://developer.apple.com/library/ios/documentation/General/Reference/SwiftStandardLibraryReference/Equatable.html



Or if you want to use ===

something like this ...

protocol RecordingObserver {
    func aFunc()
}

class MyClass: RecordingObserver {
    func aFunc() {
        // Do something
    }
}

func areEqual(a: MyClass, b: MyClass){
    if a === b {
        println("Equal")
    }
}

      

+3


source


I believe there is an isEqual method in NSObject. If your custom objects are both subclasses, you can compare a.isEqual(b)

.

+1


source


This is because you said you only implement objects RecordingObserver

. So the compiler doesn't know if it can compare them.

Try the following:

func areEqual<T where T: Equatable, T: RecordingObserver>(a: T,b: T) {

}

      

You can simply copy this code into a single view project to test:

protocol RecordingObserver {

}

class SomeClass: NSObject, RecordingObserver {
}

class ViewController: UIViewController {

    func areEqual<T where T: Equatable, T: RecordingObserver>(a: T,b: T) -> Bool {
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let a = SomeClass()
        let b = SomeClass()

        NSLog("\(areEqual(a, b: b))")
    }

}

      

0


source







All Articles