在 Swift 中调用实例方法错误消息没有完全匹配

mgy*_*yky 13 xcode swift swift5

我以前从未得到过这个,Swift 中此错误消息的含义是什么:

No exact matches in call to instance method 'dataTask(with:completionHandler:)'
Run Code Online (Sandbox Code Playgroud)

这是我的代码块:

var request: NSMutableURLRequest? = nil
let task = URLSession.shared.dataTask(
            with: request,
            completionHandler: { data, response, error in
                DispatchQueue.main.async(execute: {
                  /// ...
                })
            })
        task.resume()
Run Code Online (Sandbox Code Playgroud)

错误报告

通过feedbackassistant.apple.com 报告:

FB7717686

mgy*_*yky 17

为什么Xcode大喊大叫?

也许消息文本似乎有点不言自明,但仅仅因为 Xcode 并没有完全指向参数本身,所以第一次有点难以想象。

Xcode 大喊大叫,因为该方法希望在方法调用中查看确切的参数类型,就这么简单。

示例案例的解决方案:

var request: URLRequest? = nil

let task = URLSession.shared.dataTask(
            with: request!,
            completionHandler: { data, response, error in
                DispatchQueue.main.async(execute: {

                })
            })
        task.resume()
Run Code Online (Sandbox Code Playgroud)

只是使用了URLRequest而不是NSMutableURLRequest

SwiftUI 示例的解决方案

假设这是您的用户界面:

        ZStack() {
            Image(systemName: "photo")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .background(Color.green)
                .foregroundColor(Color.white)
                .cornerRadius(12)
            Text(getToday())
                .font(.headline)
            }
        }
Run Code Online (Sandbox Code Playgroud)

这是您在 Text(...) 中调用的方法:

    func getToday() -> Any?
    {
        let now = Date()
        let calendar = Calendar.current
        let components = calendar.dateComponents([.day], from: now)
        return components.day

    }
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,解决方案将更改Any?到一个字符串类型。

调用实例方法 '* * *' 时没有完全匹配

这是一般错误消息在方法调用中使用错误类型。这就是为什么我在这里添加以帮助其他人。

我希望这个答案对你们中的一些人有所帮助。

最好的事物。

  • 大约两年后,该错误仍然以同样令人困惑的方式出现在 Xcode 12.4 中:我正在使用 `session.dataTask(with: url)` 但尚未更改周围的函数来传递 url(`url` 未声明)这就是我得到的错误,即使 `dataTask(with:) 存在。 (3认同)
  • 您可能想向 Apple 提交错误报告。当然,诊断可能比这更好。 (2认同)

小智 5

I was using dataTask with URL, but I was unwrapping the URL as NSURL, and that is why it was giving me an error.

I was doing this:

if let url = NSURL(String: "http://myyrl.com/filename.jpg") {
      //my code
}
Run Code Online (Sandbox Code Playgroud)

What fixed the error was replacing NSURL with URL:

if let url = URL(String: "http://myyrl.com/filename.jpg") {
      //my code 
}
Run Code Online (Sandbox Code Playgroud)


Nel*_*elu 5

如果您在元素中遇到此错误Text,请尝试将您的值包装String(describing: value)在. 修复了我的情况。

Text("Leading text \(String(describing: value))")
Run Code Online (Sandbox Code Playgroud)

来源