I have the following json
{
[
{
"id": "c200",
"dia": "Lunes",
"horario": "07:30/09:20",
"materia": "Dibujo Tecnico (T)",
"seccion": "A",
"profesor" : "Ernesto Arce",
"aula" : "D1"
},
{
"id": "c383",
"dia": "Martes",
"horario": "20:00/21:50",
"materia": "Sistemas de Telefonia (T)",
"seccion": "A",
"profesor" : "-",
"aula" : "CITEC"
},
{
"id": "c486",
"dia": "Miercoles",
"horario": "20:00/21:50",
"materia": "Materiales 1 (T)",
"seccion": "A",
"profesor" : "Gustavo Roman",
"aula" : "F3"
}
]
}
What I do is convert this Json into a Dictionary Array so that I can access the values of each one. I do that with the help of my following code
import UIKit
import Alamofire
extension MockData {
static func index(completion: @escaping ([MockData]) -> Void) {
Alamofire.request("https://www.dropbox.com/s/fem028u5ok95270/Clases.json?dl=1") .responseJSON { (response) in
print(response)
var users = [MockData]()
if let objects = response.result.value {
let json = objects as! NSDictionary
let list = json["Horario"] as? [[String: AnyObject]]
for object in list! {
users.append(MockData(dictionary: object))
}
}
completion(users)
}
}
}
import UIKit
class MockData: NSObject {
var id : String?
var dia : DiasClases?
var materia : String?
var horario : String?
var seccion : String?
var profesor : String?
//var aula : String?
//var obs : String?
var HorarioArray = [MockData]()
init(dictionary: [String: AnyObject]){
self.id = dictionary["id"] as? String
self.dia = dictionary["dia"] as? DiasClases
self.materia = dictionary["materia"] as? String
self.horario = dictionary["horario"] as? String
self.seccion = dictionary["seccion"] as? String
self.profesor = dictionary["profesor"] as? String
//self.aula = dictionary["aula"] as? String
//self.obs = dictionary["obs"] as? String
}
}
enum DiasClases {
case Lunes
case Martes
case Miercoles
case Jueves
case Viernes
case Sabado
static func AllValues() -> [DiasClases] {
return [Lunes, Martes, Miercoles, Jueves, Viernes, Sabado]
}
}
The problem I have is that when I debug my program and verify that the array is loaded with the correct data, the day item does not contain anything, it only says ClassDays? and I do not save the value of the day. I would greatly appreciate your help. Cheers!
In the JSON, day is not of type DiaClases, it is of type String. What you have to do is first get the day and then convert it to the corresponding DiaClases. In the init take the day and then save it as it should be
Using the following code:
You get the Enumerator that corresponds to the value you pass to it with
dictionary["dia"]
.In order to use this method in enumerators with types other than
String
you must declare themRawValue
as follows:Example with Int:
First we define which is the one
RawValue
of the enumerators in the following way:Once you have those
RawValue
declared, we can use the statement to look up the enumerator of the value you pass to it:Example searching for Wednesday: