How to use an Swift object method as a closure?

∥☆過路亽.° 提交于 2019-12-08 12:52:47

问题


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.


回答1:


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 = self.dynamicType.launch(self)

        // ...
    }
}

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



来源:https://stackoverflow.com/questions/34007809/how-to-use-an-swift-object-method-as-a-closure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!