In objC, I'd use value forKey...
Seems you are infected by some bad examples. You should use `objectForKey:` in Objective-C, unless you are trying to implement some KVC-compliant feature. Or else, you can use subscript (`[...]`), which implicitly calls `objectForKeyedSubscript:` in modern Objective-C.
And you always use subscript to access a value for a specific key of Swift Dictionary.
(I do strongly recommend you to learn very basic parts of Swift before writing actual code. It seems you are very near trying to learn English without learning how to read/write alphabets.)
for train in self.trainArray {
let car = train["Car"] as? String ?? "*car unspecified*"
let group = train["Group"] as? String ?? "*group unspecified"
let destinationCode = train["DestinationCode"] as? String ?? "*destinationCode unspecified*"
//...
print(car, group, destinationCode/*, ... */)
}
But, as I wrote before, you should better try using Codable, unless you have some reason to avoid it.
Preparing two Codable types:
struct JsonResult: Codable {
var trains: [Train]
private enum CodingKeys: String, CodingKey {
case trains = "Trains"
}
}
struct Train: Codable {
var car: String
var group: String
var destinationCode: String
var min: String
var destination: String
var line: String
var destinationName: String
var locationName: String
var locationCode: String
private enum CodingKeys: String, CodingKey {
case car = "Car"
case group = "Group"
case destinationCode = "DestinationCode"
case min = "Min"
case destination = "Destination"
case line = "Line"
case destinationName = "DestinationName"
case locationName = "LocationName"
case locationCode = "LocationCode"
}
}
(You may need to fix some types of proerties, for example, `String?` instead of `String`.)
And you can use them as:
var trainArray: [Train] = []
func processResponse(using data: Data) {
do {
let jsonResult = try JSONDecoder().decode(JsonResult.self, from: data)
guard !jsonResult.trains.isEmpty else {
print("Result is not a valid JSON object")
//You may need to handle error
return
}
trainArray = jsonResult.trains
buildDetailsForMap()
configureTable()
} catch {
print("Could not parse loaded json with error:\(error)")
//You may need to handle error
}
}
Maybe it is easier for you to access the proerties of `Train` than accessing Dictionary of Swift.