Jonathan Allen Grant
Jonathan Allen Grant

Reputation: 3668

Swift: Method is unaware that it takes in a String

I am making a JSON Parser class distinct for my project. I have a method called JSONFromURL that takes in a String and returns the optional NSDictionary?. However, when I call the method from a different class, I get the compiler error: Cannot invoke 'JSONFromURL' with argument list of type '(String)'

Here is my JSONFromURL Method:

func JSONFromURL(url: String) -> NSDictionary? {
        var endpoint = NSURL(string: url)
        var data = NSData(contentsOfURL: endpoint!)

    do {
        let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
        // use jsonData
        return jsonData
    } catch {
        // report error
    }
    return nil //returns nil, no JSON was found
}

And here is how I am calling it from a separate class:

if let users = JSONParser.JSONFromURL("https://api.myjson.com/bins/2nkay") {}

Even though I have the if statement, I still get the error. I'd like to understand why this is happening, and how to avoid it in the future.

Upvotes: 0

Views: 42

Answers (1)

Jonathan Allen Grant
Jonathan Allen Grant

Reputation: 3668

I defined an instance method instead of a type method. Adding class before the function declaration worked. class func JSONFromURL(url: String) -> NSDictionary? {...}

Upvotes: 1

Related Questions