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 ...
随机推荐
- Proteomes of paired human cerebrospinal fluid and plasma: Relation to blood-brain barrier permeability in older adults (文献分享一组-潘火珍)
题目:Proteomes of paired human cerebrospinal fluid and plasma: Relation to blood-brain barrier permeab ...
- java并发编程(一)
java并发编程(一) 线程基础 在Java代码中,单独创建线程,都需要使用类java.lang.Thread,通常可以通过集成并扩展Thread的run()方法,也可以来创建一个Thread,将一个 ...
- A - Musical Theme + 二分
#include <bits/stdc++.h> using namespace std; #define LS 2*i #define RS 2*i+1 #define UP(i,x,y ...
- java的无序机制
简单说一下上面提到的无序写,这是jvm的特性,比如声明两个变量,String a; String b; jvm可能先加载a也可能先加载b.同理,instance = new Singleton();可 ...
- 在centos7下搭建nginx环境,并配置负载均衡,最终能达到通过域名直接访问的目的
1.关于nginx:个人理解的nginx它的主要用途就是负载均衡,当然可能还有其他一些功能可能我们不长用到,我们通过nginx可以干什么呢?为什么要引入它呢?原因是当有高并发访问服务器时,服务器可能会 ...
- jmeter beanshell处理请求响应结果时Unicode编码转为中文
在Test Plan下创建一个后置BeanShell PostProcessor,粘贴如下代码即可: String s=new String(prev.getResponseData()," ...
- 洛谷 P4549 【模板】裴蜀定理
https://www.luogu.org/problemnew/show/P4549 (1)证明方程ax+by=gcd(a,b)(a,b为常数;a>0,b>0;a,b,x,y为整数)有解 ...
- morphia(5)-删除
@Test public void delete() throws Exception { final Query<Employee> query = datastore.createQu ...
- Jquery EasyUI 中ValidateBox验证框使用讲解(转)
Validatebox(验证框)的设计目的是为了验证输入的表单字段是否有效.如果用户输入了无效的值,它将会更改输入框的背景颜色,并且显示警告图标和提示信息.该验证框可以结合form(表单)插件并防止表 ...
- CSS选择器手册
CSS选择器手册 选择器 选择器名称 例子 例子描述 CSS E.class 类选择器 E.intro 选择 class="intro" 的所有E元素. ...