Advertisement
Larme

Untitled

Dec 11th, 2020
744
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.62 KB | None | 0 0
  1. let initialJSONString = """
  2. [
  3. {
  4. "id" : 1023,
  5. "price" : "89.50",
  6. "stock_quantity" : 7,
  7. "virtual" : false,
  8. "attributes" : [
  9. {
  10. "id" : 2,
  11. "option" : "XL",
  12. "name" : "Size"
  13. },
  14. {
  15. "id" : 1,
  16. "option" : "Black",
  17. "name" : "Color"
  18. }
  19. ],
  20. "sale_price" : "",
  21. "shipping_class_id" : 0
  22. },
  23. {
  24. "id" : 1022,
  25. "price" : "89.50",
  26. "stock_quantity" : 7,
  27. "virtual" : false,
  28. "date_on_sale_to" : null,
  29. "attributes" : [
  30. {
  31. "id" : 2,
  32. "option" : "XL",
  33. "name" : "Size"
  34. },
  35. {
  36. "id" : 1,
  37. "option" : "Virtual Pink/Black",
  38. "name" : "Color"
  39. }
  40. ],
  41. "sale_price" : "",
  42. "shipping_class_id" : 0
  43. }
  44. ]
  45. """
  46.  
  47. struct Cloth: Codable {
  48.     let id: Int
  49.     let price: String
  50.     let stockQuantity: Int
  51.     let virtual: Bool
  52.     let attributes: [Attributes]
  53.     let salePrice: String
  54.     let shippingClassId: Int
  55.  
  56.     struct Attributes: Codable {
  57.         let id: Int
  58.         let option: String //If you have limited values, you can use an enum String here
  59.         let name: String
  60.     }
  61. }
  62.  
  63. func parseClothes() {
  64.     let jsonData = initialJSONString.data(using: .utf8)!
  65.     do {
  66.         let decoder = JSONDecoder()
  67.         decoder.keyDecodingStrategy = .convertFromSnakeCase
  68.         let clothes = try decoder.decode([Cloth].self, from: jsonData)
  69.  
  70.         print(clothes)
  71.  
  72.         let filtered = clothes.filter { aCloth in
  73.             let attributes = aCloth.attributes
  74.             return attributes.contains { $0.name == "Color" && $0.option == "Black" }
  75.                 && attributes.contains { $0.name == "Size" && $0.option == "XL" }
  76.         }
  77.         print(filtered)
  78.     } catch {
  79.         print("Error: \(error)")
  80.     }
  81. }
  82.  
  83. parseClothes()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement