Checking if a Swift class conforms to a protocol and implements an optional function?

后端 未结 2 1434
青春惊慌失措
青春惊慌失措 2021-02-07 06:46

I\'m writing a helper function in Swift for use in SpriteKit games that will check if the collision detention has been set up correctly.

I want to check that my GameScen

2条回答
  •  走了就别回头了
    2021-02-07 07:03

    respondsToSelector fails, because it expects an instance of SKPhysicsContact and not SKPhysicsContact.type.

    To check if an object implements an interface, you can use is. So for example:

    protocol Test {
        func foo();
    }
    
    class TestImpl : Test {
        func foo() {
            print("bar")
        }
    }
    
    let a = TestImpl()
    let b = String()
    print(a is Test) // true
    print(b is Test) // false
    

提交回复
热议问题