conformsToProtocol不会使用自定义协议进行编译

AJ9*_*AJ9 6 protocols ios swift

我想检查一个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)
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

Cannot convert value of type '(myprotocol).Protocol' (aka 'myprotocol.Protocol') to expected argument type 'Protocol'

操场

我究竟做错了什么?

Rob*_*ier 12

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

let result = vc is MyProtocol
Run Code Online (Sandbox Code Playgroud)

或者as?:

if let myVC = vc as? MyProtocol { ... then use myVC that way ... }
Run Code Online (Sandbox Code Playgroud)

但要使用conformsToProtocol,您必须标记协议@objc:

@objc protocol MyProtocol {
    func myfunc()
}
Run Code Online (Sandbox Code Playgroud)

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