本文介绍了候选人不是"@objc",但协议要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在关注教程学习快速& iOS应用开发.在协议"部分中,教程定义了以下协议:

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

@objc protocol Speaker {
  func Speak()
  optional func TellJoke()
}

它表示如果您想使用可选方法创建协议,则必须在协议前加上@objc标记(即使您的类未与Objective-C互操作).

然后,它显示了实现协议的示例:

Then, it shows the sample to implement the protocol:

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

我在xcode游乐场中尝试了上面的代码,但是遇到了编译器错误类型Vicki不符合协议议长" .

I tried the above code in my xcode playground, but I got the compiler error "Type Vicki doesn't conform to protocol Speaker".

Xcode还会弹出一个修复文本,内容为候选者不是'@objc',但协议需要它"..

Xcode also pops up an fix-it text which says "Candidate is not '@objc' but protocol requires it".

我现在完全感到困惑,本教程根本没有提到此错误.有人可以向我解释所有这些以便使我清楚吗?谢谢!

I get completely confused now, the tutorial doesn't mention this error at all. Could someone please explain to me all this to make me clear? Thanks!

推荐答案

据我所知,将协议标记为@objc意味着实现该协议的所有类也必须公开给Objective-C.可以通过使Vicki成为NSObject的子类来实现:

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 {

或通过将每个已实现的方法标记为@objc:

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?")
    }
}

更新:从Apple的 Swift语言文档

Update: From Apple's Swift Language Documentation

...

还请注意,@ objc协议只能由类采用,而不能由类采用 通过结构或枚举.如果您在以下方式中将协议标记为@objc 为了指定可选要求,您将只能申请 该协议来分类类型.

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.

这篇关于候选人不是"@objc",但协议要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:45