Valonaut
Valonaut

Reputation: 29

Array from a jsonDecoder object

This might be a very easy question (sorry!).

I would like to links a mySQL database to a Quiz App in Swift 4. Therefore I connected to a service.php and got the information with decodable.

How can I access this information to show in a label? Do I have to make a new Array and append the objects?

import UIKit

struct Question: Codable {

let id: String?
let frage: String?
let antwort1: String?
let antwort2: String?
let antwort3: String?
let antwort4: String?
let correct: String?
let notiz: String?
let lernsektorID: String?
let lerneinheitID: String?
let lernbereichID: String?
let schwierigkeitID: String?
let redakteur: String?
let createdAt: String?

enum CodingKeys: String, CodingKey {
    case id = "ID"
    case frage = "Frage"
    case antwort1 = "Antwort1"
    case antwort2 = "Antwort2"
    case antwort3 = "Antwort3"
    case antwort4 = "Antwort4"
    case correct = "Correct"
    case notiz = "Notiz"
    case lernsektorID = "LernsektorID"
    case lerneinheitID = "LerneinheitID"
    case lernbereichID = "LernbereichID"
    case schwierigkeitID = "SchwierigkeitID"
    case redakteur = "Redakteur"
    case createdAt = "created_at"
}
}

var fragen = [Question]()

let url = "https://redaktion.pflegonaut.de/service.php"
let urlObj = URL(string: url)

URLSession.shared.dataTask(with: urlObj!) { (data, response, error) in
do {
     self.fragen = try JSONDecoder().decode([Question].self, from: data!)
// can I use .append() here?
// maybe in a for loop?

} catch {
    print(error)
}
}.resume()

So I can use the elements like:

//
// let randomizedQuestion = fragen.frage.randomElement()
// 
// questionOutlet.text = randomizedQuestion

Thanks!

Upvotes: 0

Views: 235

Answers (1)

vadian
vadian

Reputation: 285069

// NECESSARY? var QuestionBankJson: [QuestionJson] { var questionListJson = [QuestionJson]() }

No, just declare one array and name the struct simply Question

var questions = [Question]()

and assign

do {
  self.questions = try JSONDecoder().decode([Question].self, from: data!)
  print(self.questions[1].Frage!) 
} catch {
    print(error) // never print something meaningless like "we got an error"
}

Notes:

  • Please conform to the naming convention that variable names start with a lowercase letter.
  • If you are responsible for the JSON declare also the keys lowercased otherwise use CodingKeys.
  • Declare the struct members as much non-optional as possible.
  • Never print a meaningless literal string when catching Codable errors. Print always the error instance.
  • Use a better date string format than this arbitrary German format. UNIX time stamp, SQL date string or ISO8601 are sortable and can be even decoded to Date.

Upvotes: 1

Related Questions