簡體   English   中英

斯威夫特:實例方法作為關閉不起作用

[英]Swift: Instance method as closure not working

var closureA: (String)->()

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

let a = Test()

closureA = Test.instanceMethod(a)

closureA("hello")

Xcode10 Playground顯示錯誤:

錯誤:無法將類型'(String)->()'的值分配給類型'(String)->()'的閉包A = Test.instanceMethod(a)

我已經讀過: https : //oleb.net/blog/2014/07/swift-instance-methods-curried-functions/

我認為您缺少閉包的要點,不能將函數存儲在閉包中,但是可以使用傳遞到閉包中的變量來存儲調用函數的代碼段,並且該函數仍需要一個類實例來調用它,所以應該像這樣:

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")

我認為這是操場上的蟲子。 如果我們創建一個臨時閉包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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM