【发布时间】:2020-06-05 12:23:10
【问题描述】:
我有一个带有闭包函数的类。
class MyFetcher {
public func fetchData(searchText: String,
onResponse: @escaping () -> (),
showResult: @escaping (String) -> ())
}
}
下面这样称呼就好了
class ViewController: UIViewController {
private func fetchData(searchText: String) {
wikipediaFetcher.fetchData(searchText: searchText,
onResponse: stopIndicationAnimation,
showResult: showResult)
}
private func stopIndicationAnimation() {
// Do something
}
private func showResult(data: String) {
// Do something
}
}
但是,当我将闭包更改为MyFetcher 的类参数时,如下所示
class MyFetcher {
private let onResponse: () -> ()
private let showResult: (String) -> ()
init (onResponse: @escaping () -> (),
showResult: @escaping (String) -> ()) {
self.onResponse = onResponse
self.showResult = showResult
}
public func fetchData(searchText: String)
}
}
如下调用它会给出错误说明
Cannot convert value of type '(ViewController) -> () -> ()' to expected argument type '() -> ()'
class ViewController: UIViewController {
private let wikipediaFetcher = WikipediaFetcher(
onResponse: stopIndicationAnimation, // Error is here
showResult: showResult // Error is here
)
private func stopIndicationAnimation() {
// Do something
}
private func showResult(data: String) {
// Do something
}
我做错了什么?
【问题讨论】:
-
我发誓我以前见过这个...this 会回答你的问题吗?基本上
self在变量初始化器中不可用。