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.

recently learned about a Swift feature that blew my mind a little. Instance methods are just curried functions that take the instance as the first argument. What’s a curried function, you ask?

The basic idea behind currying is that a function can be partially applied, meaning that some of its parameter values can be specified (bound) before the function is called. Partial function application yields a new function.

Example

Consider this simple example of a class that represents a bank account:

1
2
3
4
5
6
7
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:

1
2
let account = BankAccount()
account.deposit(100) // balance is now 100

So far, so simple. But we can also do this:

1
2
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. Pay attention to the lack of parentheses after BankAccount.deposit — we are 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:

1
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.

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:

1
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?

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.

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.

For example, a Control class using target-action might look like this in Swift (adopted from a dev forums post by Jens Jakob Jensen):

Update July 29, 2014: Made the action property in TargetActionWrapper non-optional. target must be optional because it is weak.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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: (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:

1
2
3
4
5
6
7
8
9
10
11
class MyViewController {
let button = Control() func viewDidLoad() {
button.setTarget(self, action: MyViewController.onButtonTap, controlEvent: .TouchUpInside)
} func onButtonTap() {
println("Button was tapped")
}
}

Instance Methods are Curried Functions in Swift的更多相关文章

  1. Swift编程语言学习12 ——实例方法(Instance Methods)和类型方法(Type Methods)

    方法是与某些特定类型相关联的函数.类.结构体.枚举都能够定义实例方法:实例方法为给定类型的实例封装了详细的任务与功能.类.结构体.枚举也能够定义类型方法:类型方法与类型本身相关联.类型方法与 Obje ...

  2. Mongoose 'static' methods vs. 'instance' methods

    statics are the methods defined on the Model. methods are defined on the document (instance). We may ...

  3. UIView 实例方法 Instance Methods(转)

    好了,我接着上篇,开始我们的对UIView 实例方法的探索 UIView 实例方法 Instance Methods 初始化一个视图 - (id)initWithFrame:(CGRect)aRect ...

  4. [Compose] 14. Build curried functions

    We see what it means to curry a function, then walk through several examples of curried functions an ...

  5. Java SE 8 docs——Static Methods、Instance Methods、Abstract Methods、Concrete Methods和field

    一.Static Methods.Instance Methods.Abstract Methods.Concrete Methods ——Static Methods:静态方法 ——Instance ...

  6. [Ramda] Convert Object Methods into Composable Functions with Ramda

    In this lesson, we'll look at how we can use Ramda's invoker and constructNfunctions to take methods ...

  7. Static and Instance Methods in JavaScript

    class.method/instance method https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-jav ...

  8. Android JNI 学习(八):Calling Instance Methods Api

    一.GetMethodID jmethodIDGetMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig); 返回 ...

  9. Swift Standard Library: Documented and undocumented built-in functions in the Swift standard library – the complete list with all 74 functions

    Swift has 74 built-in functions but only seven of them are documented in the Swift book (“The Swift ...

随机推荐

  1. SpringBoot2.0 整合 QuartJob ,实现定时器实时管理

    一.QuartJob简介 1.一句话描述 Quartz是一个完全由java编写的开源作业调度框架,形式简易,功能强大. 2.核心API (1).Scheduler 代表一个 Quartz 的独立运行容 ...

  2. GitHub使用方法(初级)

    [初识Github] Git 是一个分布式的版本控制系统,最初由Linus Torvalds编写,用作Linux内核代码的管理.在推出后,Git在其它项目中也取得了很大成功,尤其是在Ruby社区中.目 ...

  3. 最长上升序列(Lis)

    Description A numeric sequence of ai is ordered if a1 < a2 < ... < aN. Let the subsequence ...

  4. js监听键盘提交表单

    <!DOCTYPE html> <html> <head> <title>登陆系统</title> <link href=" ...

  5. LINK fatal error LNK1123 转换到COFF期间失败

    1>LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏 全部重新生成: 0 已成功, 1 已失败, 0 已跳过 ==========解决方法如下 ...

  6. UG 常用设置

    Q01:UG制图,添加基本视图之后的中心线怎么去掉? A01:“菜单-->文件-->首选项-->制图-->视图-->公共-->常规-->□带中心线创建”,取消 ...

  7. 模拟IO 读写压力测试

    #### 本实验室通过创建一个测试表myTestTable ,分配在一个足够大小的表空间. ###然后通过 insert select 方式,创建100个后台进程进行读写操作,每个后台进程预计时间20 ...

  8. Lock简介

    digest synchronized已经提供了锁的功能,而且还是Java的内置特性,那为什么还要出现lock呢? 用一句话来讲就是——synchronized可以实现同步,但太死板了它的同步机制:l ...

  9. 119 Pascal's Triangle II 帕斯卡三角形 II Pascal's Triangle II

    给定一个索引 k,返回帕斯卡三角形(杨辉三角)的第 k 行.例如,给定 k = 3,则返回 [1, 3, 3, 1].注:你可以优化你的算法到 O(k) 的空间复杂度吗?详见:https://leet ...

  10. log4j.properties 打印到控制台 写法

    # 日志输出级别(INFO)和输出位置(stdout,R)log4j.rootLogger=INFO, stdout # 日志输出位置为控制台log4j.appender.stdout=org.apa ...