Search code examples
swiftclosures

How to use an Swift object method as a closure?


I'd like to use an object method as a closure because I need to reuse the same closure multiple times in different places in an object. Let's say I have the following:

class A {
    func launch(code: Int) -> Bool { return false }
}

And I need a closure that is of type Int -> Bool in the same object. How would I be able to use the launch method as the closure? I'd rather not do something like { self.launch($0) } if I can just directly reference the method.


Solution

  • Instance methods are curried functions which take the instance as the first argument. Therefore

    class A {
        func launch(code: Int) -> Bool { return false }
        
        func foo() {
            let cl = A.launch(self) 
            // Alternatively:
            let cl = type(of: self).launch(self)
    
            // ...
        }
    }
    

    gives you a closure of the type Int -> Bool.