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

标签 swift

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

我正在尝试这个:

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

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

最佳答案

KeyPath 用于属性。但是,您可以有效地做同样的事情。因为函数是 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”传递给任何其他类或方法,并且可以使用它。

关于swift - 是否可以创建方法的键路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47314967/

相关文章:

xcode - Swift 2 错误 : . alloc() 在 Swift 中不可用:改用对象初始值设定项

ios - UImage 加载整个 SKTextureAtlas 而不仅仅是 SKTexture

ios - 以编程方式截图并在 Swift 中模糊

objective-c - 父 handleWatchKitExtensionRequest 从未调用过?

swift - 我如何从iOS系统词典中获取单词含义

ios - CAGradientLayer 未显示?

ios - Alamofire 请求完成后如何在后台线程中解析 JSON?

arrays - 从结构体中获取相同标签的值的总和

swift - 如何在其子类中观察 UITexFiled startEditing 和 EndEditing?

ios - 在 GameScene 上画一条简单的线