Home > Blockchain >  Type 'HeroStruct.Type' cannot conform to 'Decodable', how can i solve that?
Type 'HeroStruct.Type' cannot conform to 'Decodable', how can i solve that?

Time:11-15


import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var hero = [HeroStruct]()
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
        navigationController?.navigationBar.barTintColor = UIColor.systemYellow
        navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.systemYellow ]
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: nil)
        cell.textLabel?.text = ""
        cell.backgroundColor = .systemYellow
        return cell
    }
    
    func getJsonData(completion: @escaping () -> () ) {
        
         let url  = URL(string: "https://api.opendota.com/api/heroStats")
        let task = URLSession.shared.dataTask(with: url!) { data, response, error in
            if error != nil {
                print(error?.localizedDescription)
            }else {
                
                do {
                    
                    let result = try JSONDecoder().decode(HeroStruct.Type, from: data!)
                }catch {
                    print(error)
                    
                }
                
            }
        }
  
    }
}

import Foundation

struct HeroStruct : Decodable {
    let localized_name : String
    let primary_attr : String
    let attack_type : String
    let legs : Int
    let img : String
}

First code block is my ViewController.swift page,

second code block is my HeroStruct.swift page,

I tried to get data from Json but i got error like this:

Type 'HeroStruct.Type' cannot conform to 'Decodable'

How can i solve this?

 let result = try JSONDecoder().decode([HeroStruct].Type, from: data!)`

I tried write like this but doesn't work. Need help ,thanks.

CodePudding user response:

Replace [HeroStruct].Type with [HeroStruct].self. Whenever you want to decode something, always use .self & not .Type.

  • Related