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

Mar*_*era 2 swift

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

我正在尝试:

class MyClass {
    init() {
        let myKeypath = \MyClass.handleMainAction
        ...
    }
    func handleMainAction() {...}
}
Run Code Online (Sandbox Code Playgroud)

但它没有编译说 Key path cannot refer to instance method 'handleMainAction()

Kel*_*vin 6

您可以用作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
Run Code Online (Sandbox Code Playgroud)

关键是您可以传递/存储方法引用,就像您对关键路径所做的那样。当您需要调用该方法时,您只需要提供实际实例。


Dav*_* S. 5

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

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