簡體   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