Compliance ToProtocol will not compile with user protocol

I want to check if the UIViewControllerprotocol of my own creation matches :

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?

+4
source share
1 answer

In Swift, the best solution is:

let result = vc is MyProtocol

or as?:

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

But for use, conformsToProtocolyou must note the protocol @objc:

@objc protocol MyProtocol {
    func myfunc()
}

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

+8
source

Source: https://habr.com/ru/post/1614775/


All Articles