提问者:小点点

无法将类型“(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)
    }
}

按下面的方式调用它会给出错误,说明无法转换类型'(ViewController)->的值; ()->; ()'到预期参数类型'()->; ()'

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
    }

我做错什么了吗?


共1个答案

匿名用户

出现此错误是因为您在WikiPediaFetcher可用之前将ViewController初始化为ViewController的属性。 尝试将其作为懒惰加载

class ViewController: UIViewController {

    private lazy var wikipediaFetcher = WikipediaFetcher(
        onResponse: stopIndicationAnimation,
        showResult: showResult              
    )

    private func stopIndicationAnimation() {
        // Do something
    }

    private func showResult(data: String) {
        // Do something
    }
}