chamorro951
chamorro951

Reputation: 41

Generic parameter could not be inferred

I have a method on a class in which I use a generic that is of type UIViewController and conforms to a protocol. Yet when I call this public method from another class I am receiving "Generic parameter could not be inferred". Not sure why as I've already told the method the generics type.

public func mapBlocks<T: UIViewController where T: MyProtocol>(mapper:(name: String, obj: T ) -> ()) {
   // do something
}

Error happens here when I try to call the method from another class...

MyClass.mapBlocks { (name, obj) -> () in 
   // do something
}

Upvotes: 4

Views: 2736

Answers (1)

Philipp Otto
Philipp Otto

Reputation: 4111

I know this question is very old and I really hope you solved the problem in the last one and a half years. ;-) But for everybody who stumbles over this question again here is the solution.

You need to pass the type of T to the generic method by explicitly defining the type of the closure parameters when calling the method. Here is the Swift3 example:

protocol MyProtocol {
}

class MyClass: UIViewController, MyProtocol {
}

func mapBlocks<T: UIViewController>(mapper: @escaping (String, T) -> ()) where T: MyProtocol {
}

mapBlocks { (name: String, obj: MyClass) in
}

Hope this helps!

Upvotes: 1

Related Questions