ios - conformsToProtocol 不会用自定义协议(protocol)编译

标签 ios swift protocols

我想检查 UIViewController 是否符合我自己创建的协议(protocol):

import UIKit

protocol myProtocol {
    func myfunc()
}

class vc : UIViewController {

}

extension vc : myProtocol {
    func myfunc() {
        //My implementation for this class
    }
}

//Not allowed
let result = vc.conformsToProtocol(myProtocol)

//Allowed
let appleResult = vc.conformsToProtocol(UITableViewDelegate)

但是我得到以下错误:

无法将类型“(myprotocol).Protocol”(又名“myprotocol.Protocol”)的值转换为预期的参数类型“Protocol”

Playground

我做错了什么?

最佳答案

在 Swift 中,更好的解决方案是:

let result = vc is MyProtocol

as?:

if let myVC = vc as? MyProtocol { ... then use myVC that way ... }

但是要使用conformsToProtocol,你必须标记协议(protocol)@objc:

@objc protocol MyProtocol {
    func myfunc()
}

(请注意,类和协议(protocol)应始终以大写字母开头。)

关于ios - conformsToProtocol 不会用自定义协议(protocol)编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33572254/

相关文章:

xcode - Firebase 提供商数据

ios - 使用协议(protocol) - 如何将消息发送回 ViewController?

ios - 委托(delegate)在使用协议(protocol)时得到 nil

iphone - 委托(delegate)和协议(protocol)无法正常工作

ios - 如何判断苹果应用内购买是后端的调试测试

ios - 使用额外的宽度或高度 iOS Swift 截取屏幕截图

ios - 基于bool预选UISegmentControl的状态

ios - 无法在 Xcode iPhone 模拟器中运行 Unity3d 应用程序

ios - 使用 AFNetworking 在服务器上保存图像不起作用

swift - 尝试添加其他文本字段时,为什么我的标签不会更改位置?