3

I implementing JSONDecoder on to get the JSON data from Wordpress json my struct is in the other swift file i get this error here's my code. on let article I get the error

URLSession.shared.dataTask(with: url!){ (data,response ,err) in
        guard let data = data else{return}
        let article = JSONDecoder.decode(LatestArticleModel , from: data)

    }.resume()

LatestArticleModel.swift

struct LatestArticleModel : Decodable {

    var id: Int
    var date: String
    var link: String
    var title_rendered :String
    var author: Int
    var category: Int
    var img_link: String
    var content_rendered: String
    var exerpt_rendered: String


}
Guren
  • 182
  • 2
  • 14
  • 2
    `JSONDecoder.decode(LatestArticleModel , from: data)` => `JSONDecoder().decode(LatestArticleModel.self , from: data)`? It's an instance method, not a class method, so you need to use an object. Like `let jsonDecoder = JSONDecoder(); jsonDecoder.decode(LatestArticleModel.self, from: data)`, and it's missing `self`. – Larme Oct 19 '18 at 09:06

2 Answers2

7

The article should be declared as:

let decoder = JSONDecoder()
let article = decoder.decode(LatestArticleModel.self , from: data)

If you check the decode(_:forKey:), you'll see that it is an instance method (not a static) which means that you should call it via an instance of JSONDecoder. Also, the type parameters is T.Type (the metatype), which means that it should be the self of the type.

Furthermore: what is T.Type in swift.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • 2
    It's also an instance method, not a class method, there is no `static` in the declaration of it. Because I think the error talk about that, not yet about the missing `self`. – Larme Oct 19 '18 at 09:12
  • It worked now thank you. I'll add this this is my code let decoder = JSONDecoder() let article = try! decoder.decode(LatestArticleModel.self, from: data) – Guren Oct 19 '18 at 09:18
3

The issue the compiler error is telling you about is that you are trying to call an instance method on a type instead of an instance of that type. You need to create an instance of JSONDecoder and call decode on that.

Once you fix that you'll also run into the issue that you need to pass a meta type to the method, so LatestArticleModel.self instead of LatestArticleModel.

let article = JSONDecoder().decode(LatestArticleModel.self, from: data)
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116