斯威夫特:实例方法作为关闭不起作用

时间:2018-11-09 04:04:37

标签: swift closures

var closureA: (String)->()

class Test {
    func instanceMethod(string: String) {
    }
}

let a = Test()

closureA = Test.instanceMethod(a)

closureA("hello")

Xcode10游乐场显示错误:

错误:无法将类型'(String)->()'的值分配给类型'(String)->()' ClosureA = Test.instanceMethod(a)

我已经阅读:https://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/

2 个答案:

答案 0 :(得分:0)

我认为您缺少闭包的要点,您无法将函数存储在闭包中,但是您可以使用传递到闭包中的变量和函数来存储调用函数的代码段仍然需要一个类实例来调用它,所以应该像这样:

var closureA: ((String)->())?

class Test {
    func instanceMethod(string: String) {
        print(string)
    }
}

let a = Test()

//Assume you have a variable `str: String` before hand that will execute the code inside closure
closureA = { str in
    a.instanceMethod(string: str)
}

//Actual call to the closure to execute it
closureA?("hello")

答案 1 :(得分:0)

我认为这是操场上的虫子。如果我们创建一个临时闭包B,并将其分配给闭包A。那么它将起作用。

var closureA: (String)->()

class Test {
    func instanceMethod(string: String) {
        print("Test")
    }
}

let a = Test()

let closureB =  Test.instanceMethod(a)

closureA = closureB

closureA("hello")   // works