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 ...
随机推荐
- 求无向图的割点和桥模板(tarjan)
一.基本概念 1.桥:若无向连通图的边割集中只有一条边,则称这条边为割边或者桥 (离散书上给出的定义.. 通俗的来说就是无向连通图中的某条边,删除后得到的新图联通分支至少为2(即不连通: 2.割点:若 ...
- IT兄弟连 JavaWeb教程 JSP语法
在JSP页面中,脚本标识使用的最为频繁,因为他们能够方便.灵活地生成页面中的动态内容,特别是JSP程序代码块.JSP中的脚本标识包括3部分,即JSP声明区.JSP表达式和JSP程序代码块.通过这些标识 ...
- scrapy.Request使用meta传递数据,以及deepcopy的使用
scrapy.Request(url[,callback,method="GET",headers,body,cookies,meta,dont_filter=False]) ...
- (十四)SpringBoot开发微信授权支付
前提:配置好域名,在公众号配置 一.引用jar包,在pom.xml文件加入依赖 <dependency> <groupId>com.github.binarywang</ ...
- 一个致命的 Redis 命令,导致公司损失 400 万
什么样的 Redis 命令会有如此威力,造成如此大的损失? 具体消息如下: 看完这个消息后,我心又一惊,为什么这么低级的问题还在犯?为什么线上的危险命令没有被禁用?这事件报道出来真是觉得很低级... ...
- iOS开发 - RunLoop理解
RunLoop概念 运行循环,一个 run loop 就是一个事件处理的循环,用来不停的调度工作以及处理事件 作用 保持程序的持续运行 监听处理App中的各种事件(触摸事件,定时器事件,selecto ...
- AOP 应用
AOP 的核心:解耦 1. 权限认证2. 事务3. 日志4. Lazy loading 懒加载5. Context Process 上下文处理6. Error Handler 错误追踪(异常捕获)7. ...
- swift SqliteDB使用
操作步骤: 1,在 Build Phases -> Link Binary With Libraries 中点击加号,添加 libsqlite3.0.tbd 到项目中来 2,创建连接头文件B ...
- STP-4-每VLAN生成树和Trunk上的STP
如果在有冗余链路且有多个VLAN的交换网络中只使用 STP实例,那么在稳定状态中,仍会有一些端口处于阻塞状态不被使用,冗余链路实际上变成了备份链路. PVST+特性能为每个VLAN创建一个STP实例. ...
- A.走方格
链接:https://ac.nowcoder.com/acm/contest/368/A 题意: 在一个n*n的方格中,你只能斜着走. 你还有一次上下左右走的机会 给你一个起点(sx,sy),和终点( ...