如何快速使用函数成员指针?

时间:2018-09-07 21:49:49

标签: swift function pointers member

我正在尝试为操作重新分配一个新值“ doo”,但出现错误“无法将类型'()->()'的值分配为'(myClass)->()->( )'“ 我该如何解决?

class myClass {

    var action = foo    //function pointer

    var actions = [foo, doo] //function pointer array

    var i = 12


    func foo() {
        print("NOP: \(i)")
    }

    func doo() {
        print("doo: \(i)")
    }

    func change()
    {

        action = actions[1] //this compiles

        //Cannot assign value of type '() -> ()' to type '(myClass) -> () -> ()'
        action = doo    //doesn't compile :(


        //... later:
        action(self)() //call the function pointer
    }

}

1 个答案:

答案 0 :(得分:2)

替换此

action = doo  

使用

action = type(of:self).doo // or myClass.doo

问题出在函数change的内部,而您在引用doo的函数self而不是类型myClass本身

相关问题