Search code examples
swiftxcodeswift5

No exact matches in call to instance method error message in Swift


I never get this before, What is the meaning of this error message in Swift:

No exact matches in call to instance method 'dataTask(with:completionHandler:)'

Here is my code block:

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

Bug Report

Reported via feedbackassistant.apple.com: FB7717686

Note: The Error still exists in the Xcode Version 14.3 on 2023, May 1


Solution

  • Why Xcode Yelling?

    Maybe the message text seems a little bit self-explanatory but because Xcode does not precisely point to the parameter itself, a little bit hard to figure out the first time.

    Xcode is yelling because the method wants to see exact parameter types on the method call, that is easy.

    Solution for the Question:

    var request: URLRequest? = nil
    
    let task = URLSession.shared.dataTask(
                with: request!,
                completionHandler: { data, response, error in
                    DispatchQueue.main.async(execute: {
    
                    })
                })
    task.resume()
    

    Just used the URLRequest instead of the NSMutableURLRequest.

    A SwiftUI Case

    Let's assume this is your UI:

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

    And this is the method that you're calling in the Text(...):

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

    Solution

    In the example above solution would be changing the Any? to a String type.

    A NSURL Case

    if let url = NSURL(String: "http://example-url.com/picture.png") {
      // ...
    }
    

    Solution

    if let url = URL(String: "http://example-url.com/picture.png") {
      // ...
    }
    

    ℹ️ No exact matches in call

    to instance method '* * *'

    This is a general error message for using the wrong type in the method calls. That's why I added here to help others.

    I hope this answer will help some of you guys.

    Best.