Max
Max

Reputation: 3439

How to pass an instance method as a closure argument to another function?

I am trying to pass an object method as a parameter to another function which is expecting a closure of same signature. I have had a look at this without any success.

// these are just dummy protocols to make my example run in Playground without include Alamofire or SwiftyJSON
public struct Response<Value, Error: ErrorType> { }
public protocol SwiftyJSONSerializable { }
public protocol ResponsePathProvider { }


class MyClass1 {
    func responseObject<T:SwiftyJSONSerializable>(keyPath path:String, completionHandler: Response<[String:T], NSError> -> Void) -> Self {
        return self
    }
}

class MyClass2 {
    func test() {
        let mc = MyClass1()
        mc.responseObject(keyPath: "/*/", completionHandler: testable) //fails
        mc.responseObject(keyPath: "/*/", completionHandler: self.dynamicType.testable(self)) //fails
    }

    func testable<T:SwiftyJSONSerializable>(response: Response<[String:T], NSError> -> Void) {
        //NOOP
    }
}

Upvotes: 1

Views: 307

Answers (1)

GetSwifty
GetSwifty

Reputation: 7756

First, the testable function should be:

func testable<T:SwiftyJSONSerializable>(response: Response<[String:T], NSError>) {
    //NOOP
}

to properly adhere to the types.

Unfortunately, I believe this is either a current limitation of generics as they relate to protocols, or a bug. If you simply change SwiftyJSONSerializable to a Class, it works.

Upvotes: 1

Related Questions