Search code examples
swiftprotocols

Find by Protocol in Swift


How can I pass a protocol as a parameter in Swift?

In Objective-C I could do this:

id <CurrentUserContex> userContex = [ServiceLocator locate:@protocol(CurrentUserContex)];

Service locator:

+ (id)locate:(id)objectType 

Edit

After Qbyte answer tried using:

ServiceLocator.locate(CurrentUserContex.self)

But I'm getting 'CurrentUserContex.Protocol' does not confirm to protocol 'AnyObject'

So I tried:

ServiceLocator.locate(CurrentUserContex.self as! AnyObject)

But then I get:

Could not cast value of type 'ApplicationName.CurrentUserContex.Protocol' (0x7fec15e52348) to 'Swift.AnyObject' (0x7fec15d3d4f8).

Solution

  • I would suggest to use this if CurrentUserContex is the name of the protocol itself:

    ServiceLocator.locate(CurrentUserContex.self)
    

    If CurrentUserContex is a variable which type is a protocol use:

    ServiceLocator.locate(CurrentUserContex)
    

    I hope this solves your problem