Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conformsToProtocol will not compile with custom Protocol

I want to check that a UIViewController conforms to a protocol of my own creation:

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)

However I get the following error :

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

Playground

What am I doing wrong?

like image 714
AJ9 Avatar asked Nov 06 '15 17:11

AJ9


1 Answers

In Swift, the better solution is is:

let result = vc is MyProtocol

or as?:

if let myVC = vc as? MyProtocol { ... then use myVC that way ... }

But to use conformsToProtocol, you must mark the protocol @objc:

@objc protocol MyProtocol {
    func myfunc()
}

(Note that classes and protocols should always start with a capital.)

like image 129
Rob Napier Avatar answered Oct 26 '22 02:10

Rob Napier