如何使用Swift对象方法作为闭包? [英] How to use an Swift object method as a closure?
本文介绍了如何使用Swift对象方法作为闭包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用对象方法作为闭包,因为我需要在对象的不同位置多次重复使用相同的闭包。让我们假设我有以下:
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 }
}
我需要一个类型 Int - > Bool
。我如何能够使用 launch
方法作为闭包?我宁愿不做像 {self.launch($ 0)}
如果我可以直接引用的方法。
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.
推荐答案
实例方法是curried函数,它将实例
作为第一个参数。因此
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)
// ...
}
}
b $ b
给你一个类型 Int - > Bool
。
这篇关于如何使用Swift对象方法作为闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文