conformsToProtocol 不会用自定义协议编译

conformsToProtocol will not compile with custom Protocol

我想检查 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'

我做错了什么?

在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()
}

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