【问题标题】:Cannot convert value of type '(ViewController) -> () -> ()' to expected argument type '() -> ()'无法将类型“(ViewController)->()->()”的值转换为预期的参数类型“()->()”
【发布时间】: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 在变量初始化器中不可用。

标签: ios swift closures


【解决方案1】:

发生错误是因为您在wikipediaFetcher 可用之前将wikipediaFetcher 初始化为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
    }
}

【讨论】:

  • 不错的一个。那会做的。我想知道我们是否还能做到let
  • 没有提供lazy let的选项。查看documentation 了解更多详情。 Swift 文档是非常好的资源。
  • 谢谢。我知道没有lazy let,但根据medium.com/@elye.project/…,只要有一种聪明的解决方法。感谢你的回答。勾选正确的。
猜你喜欢
  • 2017-01-06
  • 2016-07-27
  • 2016-07-02
  • 2016-03-21
  • 1970-01-01
  • 1970-01-01
  • 2020-03-01
  • 2016-08-01
  • 2017-02-07
相关资源
最近更新 更多