TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Parsing the model immediately in the structure?

Forums > SwiftUI

Good afternoon guys. I read somewhere that there is a way to process data in the model itself. If, for example, there are two different structures in the array, then you can select the required structure at the decoding stage. Example data

{
  "news": [
    {
      "name": "iPhone 14 Pro Max",
      "description": "",
      "data": "",
      "image": "https://www.apple.com/v/iphone-14/i/images/key-features/features/size/size_yellow__dnv9794q7loy_large.jpg"
    },
    {
      "LastName": "Maximus",
      "FirstName": "Decimus Meridius",
      "congratulation": "Сongratulations on defeating the replicants",
      "imageUser": "https://m.media-amazon.com/images/M/MV5BMTQyMTExNTMxOF5BMl5BanBnXkFtZTcwNDg1NzkzNw@@._V1_.jpg",
      "imageSecondUser": "https://resizing.flixster.com/qM3YR9xfcdZLdJuQ2eTtlZKWFn8=/300x300/v2/https://flxt.tmsimg.com/assets/p21973_i_h9_aa.jpg"
    }
  ]
}

struct New: Codable {
    let news: [News]
}

struct New: Codable {
    let name: String
    let description: String 
    let data: String
    let image: String
}

struct New: Codable {
    let lastName: String
    let firstName: String
    let congratulation: String
    let imageUser String
    let imageSecondUser: String
}

2      

You aren't going to be able to do anything with 3 different structs all called New. The compiler will throw a fit over that.

But yes, there are ways to have different types in a JSON array and still use Codable to (en|de)code it.

I gave examples of a couple of ways to achieve that in this thread: SOLVED: Can you make a non-concrete type conform to codable? – Swift – Hacking with Swift forums

Googling "swift codable heterogeneous array" will get you more examples and other ways of achieving what you want to do.

2      

Hi, mr. @roosterboy I probably did not make a request on the problem. I had a task, in the array received from the server there were various objects for filling. As in my example above. And this partition can somehow be implemented in the model. I removed the example.

2      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.