我想检查UIViewController
是否符合我自己创建的协议:
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)
但是我收到以下错误:
Cannot convert value of type '(myprotocol).Protocol' (aka 'myprotocol.Protocol') to expected argument type 'Protocol'
我做错了什么?
答案 0 :(得分:11)
在Swift中,更好的解决方案是is
:
let result = vc is MyProtocol
或as?
:
if let myVC = vc as? MyProtocol { ... then use myVC that way ... }
但要使用conformsToProtocol
,您必须标记协议@objc
:
@objc protocol MyProtocol {
func myfunc()
}
(请注意,类和协议应始终以大写字母开头。)