实例方法是Swift中的“Curried”函数
Updates:
Jul 29, 2014
Made the action property in TargetActionWrapper non-optional. target must remain optional because it’s weak.
使TargetActionWrapper中的action属性非可选。 目标必须保持可选,因为它很弱。
Nov 26, 2017
Clarified my usage of the term “curried”, which isn’t strictly correct. Updated the code to Swift 4.
澄清了我对“咖喱”一词的用法,这并非严格正确。 将代码更新为Swift 4。
An instance method in Swift is just a type method that takes the instance as an argument and returns a function which will then be applied to the instance.
Swift中的实例方法只是一种类型方法,它将实例作为参数并返回一个函数,然后将该函数应用于实例。
I recently learned about a Swift feature that blew my mind a little. Instance methods are just (partially) “curried” functions that take the instance as the first argument. What’s a curried function, you ask?
swift的一个功能让我的脑海里浮现一点。 实例方法只是(部分)“curried”函数,它将实例作为第一个参数。 你问,什么是一个咖喱函数?
Currying 柯里化
The idea behind currying (named after mathematician Haskell Curry) is that you any function that takes multiple parameters can be transformed into a chained series of fundtions that take one argument each.
currying(以数学家Haskell Curry命名)背后的想法是,任何带有多个参数的函数都可以转换为一条链在一起的函数(链式函数),每个函数都有一个参数。
For example, suppose you have function of type (Int, Double) -> String
— it takes an Int
and a Double
, and returns a String
. If we curry this function, we get (Int) -> (Double) -> (String)
, i.e. a function that takes just an Int
and returns a second function. This second function then takes the Double
argument and returns the final String
. To call the curried function, you’d chain two function calls:
例如,假设你有类型(Int,Double) - > String
的函数 - 它接受一个Int
和一个Double
类型的参数,并返回一个String
值。 如果我们curry
这个函数,我们得到(Int) - >(Double) - >(String)
的函数,即接受一个Int
类型参数然后返回一个函数。 第二个函数接受Double
参数并返回最终的String
。 要调用curried函数,你需要链接两个函数调用:
let result: String = f(42)(3.14)
// f takes an Int and returns a function that takes a Double.
Why would you want to do this? The big advantage of curried functions is that they can be partially applied, i.e. some arguments can be specified (bound) before the function is ultimately called. Partial function application yields a new function that you can then e.g. pass around to another part of your code. Languages like Haskell and ML use currying for all functions.
你为什么想做这个? curried函数的一大优点是可以部分应用它们,即在最终调用函数之前可以指定(绑定)一些参数。 部分函数应用程序会生成一个新函数,您可以将其作为例如 传递给你代码的另一部分。 像Haskell和ML这样的语言使用currying来完成所有功能。
Swift uses the same idea of partial application for instance methods. Although it’s not really accurate to say instance methods in Swift are “curried”, I still like to use this term.
Swift使用与实例方法部分应用相同的想法。 虽然说Swift中的实例方法“ curried”并不准确,但我仍然喜欢使用这个术语。
Example
Consider this simple example of a class that represents a bank account:
考虑一个代表银行帐户的类的简单示例:
class BankAccount {
var balance: Double = 0.0
func deposit(_ amount: Double) {
balance += amount
}
}
We can obviously create an instance of this class and call the deposit() method on that instance:
我们显然可以创建这个类的实例并在该实例上调用deposit()方法:
let account = BankAccount()
account.deposit(100) // balance is now 100
So far, so simple. But we can also do this:
到目前为止,这么简单。 但我们也可以这样做:
let depositor = BankAccount.deposit(_:)
depositor(account)(100) // balance is now 200
This is totally equivalent to the above. What’s going on here? We first assign the method to a variable. Note that we didn’t pass an argument after BankAccount.deposit(_:) — we’re not calling the method here (which would yield an error because you can’t call an instance method on the type), just referencing it, much like a function pointer in C. The second step is then to call the function stored in the depositor variable. Its type is as follows:
这完全等同于上述内容。 这里发生了什么? 我们首先将方法分配给变量。 请注意,我们没有在BankAccount.deposit(_ :)之后传递一个参数 - 我们没有在这里调用这个方法(因为你不能在类型上调用实例方法会产生错误),只是引用它, 很像C中的函数指针。第二步是调用存储在变量中的函数。 其类型如下:
let depositor: BankAccount -> (Double) -> ()
In other words, this function has a single argument, a BankAccount instance, and returns another function. This latter function takes a Double and returns nothing. You should recognize the signature of the deposit() instance method in this second part.
换句话说,此函数具有单个参数,即BankAccount实例,并返回另一个函数。 后一个函数采用Double并且不返回任何内容。 您应该在第二部分中识别deposit()实例方法的签名。
I hope you can see that an instance method in Swift is simply a type method that takes the instance as an argument and returns a function which will then be applied to the instance. Of course, we can also do this in one line, which makes the relationship between type methods and instance methods even clearer:
我希望你能看到Swift中的实例方法只是一个类型方法,它将实例作为参数并返回一个函数,然后将该函数应用于实例。 当然,我们也可以在一行中执行此操作,这使得类型方法和实例方法之间的关系更加清晰:
BankAccount.deposit(account)(100) // balance is now 300
By passing the instance to BankAccount.deposit(), the instance gets bound to the function. In a second step, that function is then called with the other arguments. Pretty cool, eh?
通过将实例传递给BankAccount.deposit(),实例将绑定到该函数。 在第二步中,然后使用其他参数调用该函数。 很酷,嗯?
Implementing Target-Action in Swift
Christoffer Lernö shows in a post on the developer forums how this characteristic of Swift’s type system can be used to implement the target-action pattern in pure Swift. In contrast to the common implementation in Cocoa, Christoffer’s solution does not rely on Objective-C’s dynamic message dispatch mechanism. And it comes with full type safety because it does not rely on selectors.
ChristofferLernö在[开发者论坛上的帖子](https://devforums.apple.com/message/1008188#1008188)中展示了Swift类型系统的这一特性如何用于实现[目标 - 行动模式](https 纯粹的Swift中的://developer.apple.com/library/ios/documentation/general/conceptual/Devpedia-CocoaApp/TargetAction.html)。 与Cocoa中的常见实现相反,Christoffer的解决方案不依赖于Objective-C的动态消息调度机制。 它具有全型安全性,因为它不依赖于选择器。
This pattern is often better than using plain closures for callbacks, especially when the receiving objects has to hold on to the closure for an indeterminate amount of time. Using closures often forces the caller of the API to do extra work to prevent strong reference cycles. With the target-action pattern, the object that provides the API can do the strong-weak dance internally, which leads to cleaner code on the calling side.
这种模式通常比使用普通闭包进行回调更好,特别是当接收对象必须在不确定的时间内保持闭包时。 使用闭包通常会强制API的调用者做额外的工作以防止强引用周期。 使用目标 - 动作模式,提供API的对象可以在内部执行强弱舞蹈,这样可以在呼叫方面实现更清晰的代码。
For example, a Control
class using target-action might look like this in Swift (adopted from a dev forums post by Jens Jakob Jensen):
例如,使用target-action的Control类在Swift中可能看起来像这样(从Jens Jakob Jensen的开发论坛帖子中采用):
Update July 29, 2014: Made the action property in TargetActionWrapper non-optional. target must be optional because it is weak.
2014年7月29日更新:使TargetActionWrapper中的action属性非可选。 target必须是可选的,因为它是弱引用。
protocol TargetAction {
func performAction()
}
struct TargetActionWrapper : TargetAction {
weak var target: T?
let action: (T) -> () -> ()
func performAction() -> () {
if let t = target {
action(t)()
}
}
}
enum ControlEvent {
case touchUpInside
case valueChanged
// ...
}
class Control {
var actions = [ControlEvent: TargetAction]()
func setTarget(_ target: T, action: @escaping (T) -> () -> (), controlEvent: ControlEvent) {
actions[controlEvent] = TargetActionWrapper(target: target, action: action)
}
func removeTargetForControlEvent(controlEvent: ControlEvent) {
actions[controlEvent] = nil
}
func performActionForControlEvent(controlEvent: ControlEvent) {
actions[controlEvent]?.performAction()
}
}
Usage:
class MyViewController {
let button = Control()
func viewDidLoad() {
button.setTarget(self, action: MyViewController.onButtonTap, controlEvent: .touchUpInside)
}
func onButtonTap() {
print("Button was tapped")
}
}