Search code examples
iosswiftprotocolsencapsulation

Swift check if the class has encapsulate protocol


how can I check if a class conform to encapsulate protocol?

Protocol:

@objc protocol Animation {
    func updateWithState (state: GKState)
}

Class:

class car : Entity, Animation {
}

Somewhere:

 if let myVC = entity as? Animation {
    myVC.updateWithState(nextState)
 }

works fine.


While....

Protocol:

@objc protocol Vehicle:  Animation {}

Class:

class car : Entity, Vehicle {
}

Somewhere:

 if let myVC = entity as? Animation {
    myVC.updateWithState(nextState)
 }

doesn't work, always False, never enter inside.

How can I check the protocol inside protocol?

Tanks!


Solution

  • Checking through a playground it works without issue using pure Swift so if it is not working for you then maybe something to do with the @objc bridging see the image below for working playground.

    enter image description here