简体   繁体   English

迅速-是否可以创建方法的键路径?

[英]swift - is it possible to create a keypath to a method?

Is it possible to create a keypath referencing a method? 是否可以创建引用方法的键路径? all examples are paths to variables. 所有示例都是变量的路径。

I'm trying this: 我正在尝试:

class MyClass {
    init() {
        let myKeypath = \MyClass.handleMainAction
        ...
    }
    func handleMainAction() {...}
}

but it does not compile saying Key path cannot refer to instance method 'handleMainAction() 但是它不能编译为表示Key path cannot refer to instance method 'handleMainAction()

KeyPaths are for properties. 键路径用于属性。 However, you can do effectively the same thing. 但是,您可以有效地做同样的事情。 Because functions are first class types in swift, you can create a reference to handleMainAction and pass it around: 因为函数是swift的第一类类型,所以您可以创建对handleMainAction的引用并将其传递给周围:

//: Playground - noun: a place where people can play

import UIKit
import XCTest
import PlaygroundSupport

class MyClass {
    var bar = 0

    private func handleMainAction() -> Int {
        bar = bar + 1
        return bar
    }

    func getMyMainAction() -> ()->Int {
        return self.handleMainAction
    }
}

class AnotherClass {
    func runSomeoneElsesBarFunc(passedFunction:() -> Int) {
        let result = passedFunction()
        print("What I got was \(result)")
    }
}


let myInst = MyClass()
let anotherInst = AnotherClass()
let barFunc = myInst.getMyMainAction()

anotherInst.runSomeoneElsesBarFunc(passedFunction: barFunc)
anotherInst.runSomeoneElsesBarFunc(passedFunction: barFunc)
anotherInst.runSomeoneElsesBarFunc(passedFunction: barFunc)

This will work fine, and you can pass "barFunc" to any other class or method and it can be used. 这可以正常工作,您可以将“ barFunc”传递给任何其他类或方法,并且可以使用它。

You can use MyClass.handleMainAction as an indirect reference. 您可以使用MyClass.handleMainAction作为间接引用。 It gives you a block that take the class instance as the input parameter, and returns corresponding instance method. 它为您提供了一个将类实例作为输入参数的块,并返回相应的实例方法。

let ref = MyClass.handleMainAction  //a block that returns the instance method
let myInstance = MyClass()
let instanceMethod = ref(myInstance)
instanceMethod()                    //invoke the instance method

The point is you can pass around / store the method reference just like what you did with a key path. 关键是您可以像使用键路径一样传递/存储方法引用。 You just need to supply the actual instance when you need to invoke the method. 您只需要在需要调用该方法时提供实际实例即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM