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. Elasticsearch and MongoDb

    http://www.linkedin.com/groups/Difference-between-elasticsearch-MongoDB-3393294.S.588764405916973056 ...

  2. 关于java中的不可变类(转)

    如何在Java中写出Immutable的类? 要写出这样的类,需要遵循以下几个原则: 1)immutable对象的状态在创建之后就不能发生改变,任何对它的改变都应该产生一个新的对象. 2)Immuta ...

  3. C# 文件操作 全收录 追加、拷贝、删除、移动文件、创建目录、递归删除文件夹及文件....

    本文收集了目前最为常用的C#经典操作文件的方法,具体内容如下:C#追加.拷贝.删除.移动文件.创建目录.递归删除文件夹及文件.指定文件夹下 面的所有内容copy到目标文件夹下面.指定文件夹下面的所有内 ...

  4. Nodejs 定时任务

    安装扩展:node-schedule npm install node-schedule 1.linux Crontab风格 var schedule = require('node-schedule ...

  5. LessCss学习笔记

    一.入门 1.LESSCSS是什么? LESSCSS是一种动态样式语言,属于CSS预处理语言的一种,它使用类似CSS的语法,为CSS的赋予了动态语言的特性,如变量.继承.运算.函数等,更方便CSS的编 ...

  6. jsp get与post请求乱码问题

    乱码问题01:<%reques.setCharacterEncoding("utf-8");%> 02:get请求乱码 001.:String 编码之后的字符串 = n ...

  7. intelliJ idea 下载安装

    Intellij IDEA是公认的java开发最好的工具,必须学会. 1. 打开网址 https://www.jetbrains.com/ 2. 点击 Intellij IDEA 图标连接,如下图 3 ...

  8. jQuery属性和样式操作

    回顾 1. jquery基本使用 <script src="jquery.min.js"></script><script> $(functio ...

  9. 【Android】SlidingMenu属性详解

    SlidingMenu 常用属性介绍: menu.setMode(SlidingMenu.LEFT);//设置左滑菜单menu.setTouchModeAbove(SlidingMenu.TOUCHM ...

  10. Selenium私房菜系列9 -- 我遇到的问题及解决问题的方法

    Selenium私房菜系列10 -- 我遇到的问题及解决问题的方法