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 ...
随机推荐
- Inside Geometry Instancing(上)
Inside Geometry Instancing(上) http://blog.csdn.net/soilwork/article/details/598335 翻译:claymanclayman ...
- 第三章 “我要点爆”微信小程序云开发之点爆方式页面和爆炸之音页面制作
点爆方式选择页面制作 在app.json中配置页面路径增加selectbao点爆方式选择,编译创建页面文件,点爆方式选择页面通过单选按钮组选择跳转到相应的点爆页面. <view class=&q ...
- 记一次因证书问题导致请求失败问题SSLHandshakeException
记一次因证书问题导致请求失败问题SSLHandshakeException 转载请注明出处:https://www.cnblogs.com/funnyzpc/p/10989813.html 最近接一外 ...
- PAT甲级——1135 Is It A Red-Black Tree (30 分)
我先在CSDN上面发表了同样的文章,见https://blog.csdn.net/weixin_44385565/article/details/88863693 排版比博客园要好一些.. 1135 ...
- PARTITION RANGE ALL 的优化
建议如下: 检查数据库的cpu 消耗 ,Sql_id :***** 消耗过多资源,这个新上线sql, 20号才上线,是对log 进行分析,平均每次执行时间300s.,使用的是PARTITION RAN ...
- 使用express+mongoDB搭建多人博客 学习(6)发表文章
发表文章 1.在modules文件夹下新建post.js var mongodb=require("./db"); function Post(name,title,post){ ...
- Crusher Django 学习笔记2 基本url配置
http://crusher-milling.blogspot.com/2013/09/crusher-django-tutorial2-conf-basic-url.html 顺便学习一下FQ Cr ...
- shell与aw的简单交互示例
先来看一段shell代码 word=“a test name” selectword=“test"lineitem=`echo "$word" | awk 'match( ...
- Unity Shader入门精要学习笔记 - 第9章 更复杂的光照
转载自 冯乐乐的<Unity Shader入门精要> Unity 的渲染路径 在Unity里,渲染路径决定了光照是如何应该到Unity Shader 中的.因此,如果要和光源打交道,我们需 ...
- asp.net网页跳转
1.Response.Redirect("http://www.bcbbs.net",false); 目标页面和原页面可以在2个服务器上,可输入网址或相对路径.后面的bool ...