繁体   English   中英

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

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

是否可以创建引用方法的键路径? 所有示例都是变量的路径。

我正在尝试:

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

但是它不能编译为表示Key path cannot refer to instance method 'handleMainAction()

键路径用于属性。 但是,您可以有效地做同样的事情。 因为函数是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)

这可以正常工作,您可以将“ barFunc”传递给任何其他类或方法,并且可以使用它。

您可以使用MyClass.handleMainAction作为间接引用。 它为您提供了一个将类实例作为输入参数的块,并返回相应的实例方法。

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

关键是您可以像使用键路径一样传递/存储方法引用。 您只需要在需要调用该方法时提供实际实例即可。

暂无
暂无

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

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