首页 > 解决方案 > 无法将类型“(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
    }

我做错什么了吗?

标签: iosswiftclosures

解决方案


发生错误是因为您将其初始化wikipediaFetcherViewControllerbefore 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
    }
}

推荐阅读