我想检查 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”
我做错了什么?
最佳答案
在 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/