将实例传递给实例方法可以引用该实例方法吗? [英] Passing an instance to an instance method makes a reference to that instance method?

查看:110
本文介绍了将实例传递给实例方法可以引用该实例方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在马特·诺伊伯格(Matt Neuburg)撰写的 iOS 13 Swift编程基础知识中,我遇到了这段奇怪的代码

In iOS 13 Programming Fundamentals with Swift by Matt Neuburg I came across this strange bit of code

class MyClass {
    var s = ""
    func store(_ s:String) {
        self.s = s
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        let m = MyClass()
        let f = MyClass.store(m) // what just happened!?
        f("howdy")
        print(m.s) // howdy
    }

}

显然,f的类型为() -> ()(至少在调试器上是这样),但是在下一行中,我们将字符串传递给它.

Apparently f has the type () -> () (thats what it says on debugger at least) and yet on the next line we are passing a string to it.

基于结果,似乎f某种程度上已成为对store方法的引用,这就是为什么在打印m.s时您会感到"Howdy"的原因.但是这段代码确实让我感到困惑,所以对发生的情况的解释将不胜感激.

Based of the result it seems that f has somehow become a reference to the store method which is why when m.s is printed you get "howdy". But this code really baffles me and an explanation of what is going on would be much appreciated.

我什至不了解MyClass.store的合法性,因为store是实例方法,在这种情况下,它被称为静态方法.

I don't even understand how MyClass.store is legal because store is an instance method and in this case it is being referred to as if it was a static method.

推荐答案

书中接下来的几句话告诉你答案:

The next words in the book tell you the answer:

原因是实例方法实际上是一个由两个函数组成的咖喱静态/类方法-一个函数采用一个实例,另一个函数采用该实例方法的参数.在该代码之后,f是这些函数的 second ,可以称为将参数传递给实例mstore方法的一种方式. em>

The reason is that an instance method is actually a curried static/class method composed of two functions — one function that takes an instance, and another function that takes the parameters of the instance method. After that code, f is the second of those functions, and can be called as a way of passing a parameter to the store method of the instance m.

这篇关于将实例传递给实例方法可以引用该实例方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆