conformsToProtocol将无法使用自定义协议

时间:2015-11-06 17:23:27

标签: ios swift protocols

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

Playground

我做错了什么?

1 个答案:

答案 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()
}

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