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

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 Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot 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.