ios - 无法将类型“(ViewController)->()->()”的值转换为预期的参数类型“()->()”
问题描述
我有一个带有闭包函数的类。
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
}
我做错什么了吗?
解决方案
发生错误是因为您将其初始化wikipediaFetcher
为ViewController
before it's available的属性wikipediaFetcher
。尝试将其加载为惰性
class ViewController: UIViewController {
private lazy var wikipediaFetcher = WikipediaFetcher(
onResponse: stopIndicationAnimation,
showResult: showResult
)
private func stopIndicationAnimation() {
// Do something
}
private func showResult(data: String) {
// Do something
}
}
推荐阅读
- javascript - Setter 和 value 属性无法正常工作
- java - java - 如何解决wildcardQuery elasticsearch java中的空格问题?
- c# - button.OnClick 监听器触发两次
- javascript - 带参数的 JavaScript addEventListener 函数
- javascript - 如何让整个应用程序全局可用的 MySQL 连接
- c++ - C++:获取参数包的头部和尾部
- bash - 动态 Make Dependencies 可能吗?
- oracle - Oracle DBMS_DEBUG.GET_VALUE 在调试大包时无法获取变量值
- zeromq - ZeroMQ 正在丢弃消息
- snowflake-cloud-data-platform - 在“预览应用”中,过滤器不会更新