Instance Methods are “Curried” Functions in Swift

实例方法是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<T: AnyObject> : 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<T: AnyObject>(_ 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")
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 227,401评论 6 531
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 98,011评论 3 413
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 175,263评论 0 373
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 62,543评论 1 307
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 71,323评论 6 404
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 54,874评论 1 321
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 42,968评论 3 439
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,095评论 0 286
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 48,605评论 1 331
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,551评论 3 354
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 42,720评论 1 369
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,242评论 5 355
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 43,961评论 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 34,358评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 35,612评论 1 280
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 51,330评论 3 390
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 47,690评论 2 370

推荐阅读更多精彩内容