AJ9
AJ9

Reputation: 1276

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?

Upvotes: 7

Views: 1793

Answers (1)

Rob Napier
Rob Napier

Reputation: 299455

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.)

Upvotes: 14

Related Questions