Home > front end >  How to access array of custom type with JSON data(No tableView)
How to access array of custom type with JSON data(No tableView)

Time:11-25

My mentor asked me to make simple challenge using JSON data.The idea is to make question "what is capitaly city of (country)" and answers should be placed under the question as buttons titles .

For now I've made: Struct to hold data

    struct Country : Codable{
var countries:[CountriesFinal]
   }

    struct CountriesFinal: Codable{
var country: String
var code: String
var capital: String
var region: String

} 

Array to be populated with custom date type CountriesFinal by using URLSession:

    var countriess = [CountriesFinal] ()

     session.dataTask(with: url) {[self]data,response,error in
        if let data = data {
            if let decodedResponse = try?
                JSONDecoder().decode(Country.self, from: data) {
               
                DispatchQueue.main.async {
                    // update our UI
                    countriess = decodedResponse.countries
                }                  
                return
            }
        }
        print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
    }.resume()

THIS IS THE PROBLEM

He told me concept how should I get pair values of country and its capital and later be able to shuffle them to make quiz with question containing country and one of 4 answers always be the capital we asked for and other answers be the random capitals:

From x.country and x.capital make y[i] : country and y[i] : capital. Then when I have "y" I should make a sequence of for instance 1...100 and next thing to do is just shuffle that sequence.

So listening to that concept I understand that I need to make new array or dictionary containing all values of country and capital and I don't know how to do that. I was thinking about dictionary like ["France":"Paris"] then make another array of just capitals.

I've learned how to access objects in array when using tableView but now i don't know where to start or how to make that new array with pair values because now when I try countriess.capital or country nothing happens.

I realy didnt know how else should I ask this qeustion because I'm very lost

    override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    
   
    performSelector(inBackground: #selector(fetch), with: nil)
    askQuestion()

    
}
@objc func fetch(){
let urlString = "https://raw.githubusercontent.com/djakhdjkh/json"

         let url = URL(string:urlString)!
URLSession.shared.dataTask(with: url) {[self]data,response,error in
    if let data = data {
        if let decodedResponse = try?
            JSONDecoder().decode(Country.self, from: data) {

            DispatchQueue.main.async {
                // update our UI
                countriess = decodedResponse.countries
                print(countriess[0].name)
                let index = Int.random(in: 0..<countriess.count)

    print("What is the capital of \(countriess[index].name)?")
    var choices = [index]
    while choices.count < 3 {
        let newIndex = Int.random(in: 0..<countriess.count)
       if !choices.contains(newIndex) {
           choices.append(newIndex)
       }
    }
    choices = choices.shuffled()
    print("Choices:")
    choices.forEach { _ in print(countriess[index].capital) }
                
                
                
            }
            return
        }
    }
    print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()

CodePudding user response:

If you wanted to print a question and possible choices from your countries array, the code might look something like this:

let index = Int.random(0..<countries.count)

print("What is the capital of \(countries[index].country)?")


var choices = [index]
while choices.count < 3 {
   let newIndex = Int.random(0..<countries.count)
   if !choices.contains(newIndex) {
       choices.append(newIndexP
   }
}
choices = choices.shuffled()
print("Choices:")
choices.forEach { print($0.capital) }
  • Related