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. Xmind8 Pro 思维导图制作软件,傻瓜式安装激活教程

    xmind 是做思维导图的软件?今天有一个以前的同事还在和我要这个软件,当然我支持正版啊 !因为正版好用! 我是一个不爱说废话的人,就顺便分享一下 给大家用! 软件下载地址: 链接:https://p ...

  2. JQuery:介绍、安装、选择器、属性操作、动画

    目录 jQuery 详细内容 1.JQuery介绍 2.JQuery的下载安装 3.JQuery的使用 4.jQuery的选择器 5.JQuery的属性操作 6.动画 6.自定义动画 jQuery 详 ...

  3. 最长XX序列问题小结 By cellur925

    今天我们搞一搞几个经典序列问题之间的爱♂恨♂情♂仇. 首先我们看一看LIS(最长上升子序列)(From my onenote)

  4. Android近场通信---NFC基础(五)(转)

    转自 http://blog.csdn.net/think_soft/article/details/8190463 Android应用程序记录(Android Application Record- ...

  5. 安装CocoaPods,ios的库安装工具

    1.需要ruby环境,mac pro自带了 2.终端输入:sudo gem install cocoapods

  6. nutz 使用beetl

    src目录或src同级的其他目录(比如conf)下创建 beetl.properties文件,文件内容如下 (maven项目)在resources目录下创建 RESOURCE_LOADER=org.b ...

  7. 应用日志获取-web系统

    1 场景 应用使开发写的,但应用使部署再服务器上,而开发没有ssh登陆服务器的权限. so,开发总是请运维查日志,下载日志. so and so,运维要花很多时间帮开发去搞日志. 这是件很没意义的事, ...

  8. Codeforces 1114E(简单交互)

    这里有一道老实题,大家快来踩爆它! 交互题:根据你的输出决定下一次的输入. 请听题: 管理员有个乱序数列(举例:{14, 24, 9, 19}),排序以后是个等差数列({9, 14, 19, 24}) ...

  9. c#中的特性

    c#中的特性 特性在我的理解就是在类或者方法或者参数上加上指定的标记,然后实现指定的效果. 和Java中的注解@Annotation类似. c#内置的特性之Obsolete [Obsolete(&qu ...

  10. Unity Shader入门精要学习笔记 - 第4章 学习 Shader 所需的数学基础

    摘录自 冯乐乐的<Unity Shader入门精要> 笛卡尔坐标系 1)二维笛卡尔坐标系 在游戏制作中,我们使用的数学绝大部分都是计算位置.距离.角度等变量.而这些计算大部分都是在笛卡尔坐 ...