Kaz Yoshikawa
Kaz Yoshikawa

Reputation: 1637

Checking if Any.Type conforms to a protocol in Swift

I like to check if given value of Any.Type conforms to a protocol in Swift. It seems that @objc based protocol can be checked by calling class_conformsToProtocol(), but I do not have a good idea how to check that with pure swift protocol.

// ObjC

@objc protocol MyObjcProtocol {
}

class MyObjcClass: NSObject, MyObjcProtocol {
}

class_conformsToProtocol(MyObjcClass.self, MyObjcProtocol.self) // true

// Swift

protocol MySwiftProtocol: AnyObject {
}

class MySwiftClass: MySwiftProtocol {
}

class_conformsToProtocol(MySwiftClass.self, MySwiftProtocol.self) // error

If it is the case of an instance, I can check with if let object = object as? MySwiftProtocol { ... } type of approach, but Any.Type cannot be the case.

Thanks...

Upvotes: 3

Views: 5511

Answers (2)

Agent Smith
Agent Smith

Reputation: 2913

The function class_conformsToProtocol(_:_:) is an Objective-C Runtime Library function so to use it the parameters provided must have a representation to Objective C.

Like when providing selector using #selector() asks and we have to provide @objc before the method declaration So that, that particular method can be represented in Objective-C.

You can find more about it in Apple Docs for Objective-C Runtime

For checking if a class confirms a protocol you can try this:

protocol MySwiftProtocol: AnyObject {
}

class MySwiftClass: MySwiftProtocol {
}

if let mySwiftProtocol = MySwiftClass() as? MySwiftProtocol {
    //do stuff if confirms protocol
} else {
    //do stuff if doesn't confirm protocol
}

Upvotes: -1

rmaddy
rmaddy

Reputation: 318774

To check the pure Swift code, you can do:

protocol MySwiftProtocol: AnyObject {
}

class MySwiftClass: MySwiftProtocol {
}

if MySwiftClass.self as? MySwiftProtocol.Type != nil {
    print("conforms")
} else {
    print("does not conform")
}

or more simply:

if MySwiftClass.self is MySwiftProtocol.Type {

Upvotes: 9

Related Questions