Advertisement
Larme

Untitled

May 5th, 2022
1,408
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.36 KB | None | 0 0
  1.     do {
  2.         let data = Data(json.utf8)
  3.         let response = try JSONDecoder().decode(Event.self, from: data)
  4.         if let period = response.response?.output?.periods?.period {
  5.             for aPeriod in period {
  6.                 let tDetail = aPeriod.details?.tDetail
  7.                 switch tDetail {
  8.                 case .tDetailElement(let singleElement):
  9.                     print("It's a single element")
  10.                     print("Std: \(singleElement.std) - Sta: \(singleElement.sta)")
  11.                 case .tDetailElementArray(let multipleElements):
  12.                     print("It's a multiple element")
  13.                     for aSingleElement in multipleElements {
  14.                         print("Std: \(aSingleElement.std) - Sta: \(aSingleElement.sta)")
  15.                     }
  16.                 default:
  17.                     break
  18.                 }
  19.             }
  20.         }
  21.     } catch {
  22.         print("Error while decoding: \(error)")
  23.     }
  24.  
  25.  
  26. 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):
  27.  
  28. With model change (I didn't do the encode, in case you need it):
  29.  
  30.     struct Details: Codable {
  31.         let tDetail: [TDetailElement]
  32.         enum CodingKeys: String, CodingKey {
  33.             case tDetail = "TDetail"
  34.         }
  35.  
  36.         init(from decoder: Decoder) throws {
  37.             let container = try decoder.container(keyedBy: CodingKeys.self)
  38.             if let asSingleElement = try? container.decode(TDetailElement.self, forKey: .tDetail) {
  39.                 self.tDetail = [asSingleElement] //Transform it into an array of one element
  40.             } else {
  41.                 let asArray = try container.decode([TDetailElement].self, forKey: .tDetail)
  42.                 self.tDetail = asArray
  43.             }
  44.         }
  45.     }
  46.  
  47.    do {
  48.         let data = Data(json.utf8)
  49.         let response = try JSONDecoder().decode(Event.self, from: data)
  50.         if let period = response.response?.output?.periods?.period {
  51.             for aPeriod in period {
  52.                 if let tDetails = aPeriod.details?.tDetail {
  53.                     for aTDetail in tDetails {
  54.                         print("Std: \(aTDetail.std) - Sta: \(aTDetail.sta)")
  55.                     }
  56.                 }
  57.             }
  58.         }
  59.     } catch {
  60.         print("Error while decoding: \(error)")
  61.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement