UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free 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.