GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

How to sort Swift Data by the original order of a decoded JSON array

Forums > Swift

I'm building a TabView where each tab needs to appear in a specific order. The content for the tabs is fetched as JSON when the app loads and cached using Swift Data.

This is my simplified JSON for the tabs:

{
  "tabs": [
    {
      "id": "7f2769e3-9dbe-4776-a79f-268a4c06fdc0",
      "title": "Tab 1"
    },
    {
      "id": "1c8ef7c9-9b1b-4658-b8a2-b463f8f7de6f",
      "title": "Tab 2"
    }
  ]
}

The decoding and storage of the array data is working fine, however the tabs are ordered inconsistently when I query them.

How do I enforce the original order of the JSON? Is there something I can do at the decoding stage or do I need to explicity provide the order of each tab with an additional property, e.g. order, and ensure my @Query sorts by this new property?

2      

Hacking with Swift is sponsored by Proxyman.

SPONSORED Debug 10x faster with Proxyman. Your ultimate tool to capture HTTPs requests/ responses, natively built for iPhone and macOS. You’d be surprised how much you can learn about any system by watching what it does over the network.

Try Now!

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.