Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- do {
- let data = Data(json.utf8)
- let response = try JSONDecoder().decode(Event.self, from: data)
- if let period = response.response?.output?.periods?.period {
- for aPeriod in period {
- let tDetail = aPeriod.details?.tDetail
- switch tDetail {
- case .tDetailElement(let singleElement):
- print("It's a single element")
- print("Std: \(singleElement.std) - Sta: \(singleElement.sta)")
- case .tDetailElementArray(let multipleElements):
- print("It's a multiple element")
- for aSingleElement in multipleElements {
- print("Std: \(aSingleElement.std) - Sta: \(aSingleElement.sta)")
- }
- default:
- break
- }
- }
- }
- } catch {
- print("Error while decoding: \(error)")
- }
- But in my opinion, with your current example, if would be simple to not have the `enum` since you have the same element (in an array of directly):
- With model change (I didn't do the encode, in case you need it):
- struct Details: Codable {
- let tDetail: [TDetailElement]
- enum CodingKeys: String, CodingKey {
- case tDetail = "TDetail"
- }
- init(from decoder: Decoder) throws {
- let container = try decoder.container(keyedBy: CodingKeys.self)
- if let asSingleElement = try? container.decode(TDetailElement.self, forKey: .tDetail) {
- self.tDetail = [asSingleElement] //Transform it into an array of one element
- } else {
- let asArray = try container.decode([TDetailElement].self, forKey: .tDetail)
- self.tDetail = asArray
- }
- }
- }
- do {
- let data = Data(json.utf8)
- let response = try JSONDecoder().decode(Event.self, from: data)
- if let period = response.response?.output?.periods?.period {
- for aPeriod in period {
- if let tDetails = aPeriod.details?.tDetail {
- for aTDetail in tDetails {
- print("Std: \(aTDetail.std) - Sta: \(aTDetail.sta)")
- }
- }
- }
- }
- } catch {
- print("Error while decoding: \(error)")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement