Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read and display a dictionary from JSON?

I am working on an app that fetches the data from JSON and displays it.
However, I am stuck with an error saying Instance method 'appendInterpolation(_:formatter:)' requires that '[String : Int]' inherit from 'NSObject'

Here is my data structure:

struct Data: Codable {
    var message: String
    var data: Objects
}

struct Objects: Codable {
    var date: String
    var day: Int
    var resource: String
    var stats, increase: [String: Int]
}

Function to fetch the data:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

func getData() {
    let urlString = "https://russianwarship.rip/api/v1/statistics/latest"
    let url = URL(string: urlString)
    
    URLSession.shared.dataTask(with: url!) { data, _, error in
        if let data = data {
            do {
                let decoder = JSONDecoder()
                let decodedData = try decoder.decode(Data.self, from: data)
                self.data = decodedData
            } catch {
                print("Hey there's an error: \(error.localizedDescription)")
            }
        }
    }.resume()
}

And a ContentView with the @State property to pass the placeholder data:

struct ContentView: View {

@State var data = Data(message: "", data: Objects(date: "123", day: 123, resource: "", stats: ["123" : 1], increase: ["123" : 1]))


var body: some View {
    VStack {
        Button("refresh") { getData() }
        Text("\(data.data.date)")
        
        Text("\(data.data.day)")
        
        Text(data.message) 
        
        Text("\(data.data.stats)") //error is here
        

Here is an example of JSON response

JSON Str

I wonder if the problem is in data structure, because both

Text("\(data.data.date)")            
Text("\(data.data.day)")

are working just fine. If there are any workarounds with this issue – please, I would highly appreciate your help!:)

>Solution :

stats is [String: Int], and so when you want to use it, you need to supply the key to get the value Int, the result is an optional that you must unwrap or supply a default value in Text

So use this:

 Text("\(data.data.stats["123"] ?? 0)")

And as mentioned in the comments, do not use Data for your struct name.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading