Candidate is not '@objc' but protocol requires it

后端 未结 4 546
余生分开走
余生分开走 2021-02-13 22:33

I have been following this tutorial to learn swift & iOS app development. In the Protocol section, the tutorial defined the following protocol:

@objc protoco         


        
4条回答
  •  情话喂你
    2021-02-13 23:22

    From what I can tell, marking your protocol as @objc means that any classes implementing it also have to be exposed to Objective-C. This can be done either by making Vicki a subclass of NSObject:

    class Vicki: NSObject, Speaker {
    

    Or by marking each implemented method as @objc:

    class Vicki: Speaker {
        @objc func Speak() {
            print("Hello, I am Vicki!")
        }
        @objc func TellJoke() {
            print("Q: What did Sushi A say to Sushi B?")
        }
    }
    

    Update: From Apple's Swift Language Documentation

    Optional protocol requirements can only be specified if your protocol is marked with the @objc attribute.

    ...

    Note also that @objc protocols can be adopted only by classes, and not by structures or enumerations. If you mark your protocol as @objc in order to specify optional requirements, you will only be able to apply that protocol to class types.

提交回复
热议问题