Instance Methods are Curried Functions in Swift
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.
I 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 |
class BankAccount { |
We can obviously create an instance of this class and call the deposit()
method on that instance:
1 |
let account = BankAccount() |
So far, so simple. But we can also do this:
1 |
let depositor = BankAccount.deposit |
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 |
protocol TargetAction { |
Usage:
1 |
class MyViewController { |
Instance Methods are Curried Functions in Swift的更多相关文章
- Swift编程语言学习12 ——实例方法(Instance Methods)和类型方法(Type Methods)
方法是与某些特定类型相关联的函数.类.结构体.枚举都能够定义实例方法:实例方法为给定类型的实例封装了详细的任务与功能.类.结构体.枚举也能够定义类型方法:类型方法与类型本身相关联.类型方法与 Obje ...
- Mongoose 'static' methods vs. 'instance' methods
statics are the methods defined on the Model. methods are defined on the document (instance). We may ...
- UIView 实例方法 Instance Methods(转)
好了,我接着上篇,开始我们的对UIView 实例方法的探索 UIView 实例方法 Instance Methods 初始化一个视图 - (id)initWithFrame:(CGRect)aRect ...
- [Compose] 14. Build curried functions
We see what it means to curry a function, then walk through several examples of curried functions an ...
- Java SE 8 docs——Static Methods、Instance Methods、Abstract Methods、Concrete Methods和field
一.Static Methods.Instance Methods.Abstract Methods.Concrete Methods ——Static Methods:静态方法 ——Instance ...
- [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 ...
- Static and Instance Methods in JavaScript
class.method/instance method https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-jav ...
- Android JNI 学习(八):Calling Instance Methods Api
一.GetMethodID jmethodIDGetMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig); 返回 ...
- 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 ...
随机推荐
- numpy windows环境下载安装
由于numpy在多个平台下非常流行,以至于习惯WINDOWS环境下的用户可能找不到下载位置,更多的时候会下载到zip文件,然后需要安装编译(自然通不过) 1.http://www.scipy.org/ ...
- 原生js回到顶部
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...
- C 语言实例 - 判断元音/辅音
C 语言实例 - 判断元音/辅音 C 语言实例 C 语言实例 判断输入的字母是元音,还是辅音. 英语有26个字母,元音只包括 a.e.i.o.u 这五个字母,其余的都为辅音.y是半元音.半辅音字母,但 ...
- 大数(string 之间的快速幂)
//字符串的乘法 string multi(string a, string b){ ], len = a.length() + b.length(); memset(arr, , sizeof ar ...
- Codeforces Round #402 (Div. 2) A
Description In Berland each high school student is characterized by academic performance — integer v ...
- aix 推荐使用重启
重启os AIX 主机 推荐 shutdown –Fr 在客户一次停机维护中,发现了这个问题. 环境是ORACLE 10G RAC for AIX6,使用了HACMP管理共享磁盘. 在停机维护时间段内 ...
- game 竞赛图 缩环
[问题背景] zhx 和他的妹子(们)做游戏. [问题描述] 考虑 N 个人玩一个游戏, 任意两个人之间进行一场游戏 (共 N*(N-)/ 场) , 且每场一定能分出胜负. 现在,你需要在其中找到三个 ...
- linux增加系统监视器的快捷键
系统命令:gnome-system-monitor 可在终端输入调用 在系统相应的快捷键设置区设置即可
- hihocoder1821 取卡片游戏
思路: 博弈dp. 实现: #include <iostream> #include <algorithm> #include <cstring> using na ...
- Web 前端开发代码规范(基础)
一. 引言 对于一个多人团队来说,制定一个统一的规范是必要的,因为个性化的东西无法产生良好的聚合效果,规范化可以提高编码工作效率,使代码保持统一的风格,以便于代码整合和后期维护. 二. HTML/CS ...