Search code examples
iosswiftjsondecoder

Instance member 'decode' cannot be used on type 'JSONDecoder'; did you mean to use a value of this type instead


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


}

Solution

  • 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.