Rob Rob - 5 months ago 129
iOS Question

Swift: Is there a way to test if object cast as AnyObject conforms to Equatable?

I have an object that has keyed properties:

func value(key: String) -> AnyObject?
func setValue(value: AnyObject?, key: String)


I wish to check if the value returned from the
value
function with the same key from two different objects are
Equatable
. Swift complains because
Equatable
has a
Self
reference and can only be used in generics. Is there a way I can check to see if the
AnyObject
object returned from the
value
function conforms to
Equatable
?

Answer

Due to changes in Swift 2, I'm editing m'y answer

To check protocol conformance, simply use is keyword.

But you can't do it when the protocol is using Self (note the capital S).

So you could do:

if let myValue = myObject.value(myKey) as? Equatable {
    ...
}
Comments