Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: check if generic type conforms to protocol

Tags:

generics

swift

I have a protocol that I defined like so:

protocol MyProtocol {    ... } 

I also have a generic struct:

struct MyStruct <T>  {     ... } 

Finally I have a generic function:

func myFunc <T> (s: MyStruct<T>) -> T? {    ... } 

I'd like to test inside of the function if the type T conforms to MyProtocol. Essentially I'd like to be able to do (~ pseudocode):

let conforms = T.self is MyProtocol 

But this throws a compiler error:

error: cannot downcast from 'T.Type' to non-@objc protocol type 'MyProtocol'    let conforms = T.self is MyProtocol                   ~~~~~~ ^  ~~~~~~~~~~ 

I have also tried variations, like T.self is MyProtocol.self, T is MyProtocol, and using == instead of is. So far I haven't gotten anywhere. Any ideas?

like image 849
Alex Avatar asked Jan 24 '15 10:01

Alex


People also ask

How do you know if a type is conforms to protocol Swift?

You can check for protocol conformance only if your protocol is marked with the @objc attribute, as seen for the HasArea protocol above. This attribute indicates that the protocol should be exposed to Objective-C code and is described in Using Swift with Cocoa and Objective-C.

What is Associatedtype in Swift?

An associated type gives a placeholder name to a type that's used as part of the protocol. The actual type to use for that associated type isn't specified until the protocol is adopted. Associated types are specified with the associatedtype keyword.

What is generic protocol?

Generic Protocols are for procedures/techniques involving human participants that are used on a regular basis, and which form all or part of subsequent research projects or taught modules.


2 Answers

I have to say @Alex want to check if T type conforms to protocol rather than s. And some answerer didn't see clearly.

Check T type conforms to protocol like this :

if let _ = T.self as? MyProtocol.Type {     //  T conform MyProtocol } 

or

if T.self is MyProtocol.Type {     //  T conform MyProtocol } 
like image 57
maquannene Avatar answered Sep 29 '22 12:09

maquannene


A bit late but you can test if something responds to protocol with as ? test:

if let currentVC = myViewController as? MyCustomProtocol {     // currentVC responds to the MyCustomProtocol protocol =] } 

EDIT: a bit shorter:

if let _ = self as? MyProtocol {     // match } 

And using a guard:

guard let _ = self as? MyProtocol else {     // doesn't match     return } 
like image 24
jlngdt Avatar answered Sep 29 '22 12:09

jlngdt