NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

What is the best way to represent this data model relationship?

Forums > Swift

My app allows users to store data for individual items. There are many properties for an item, but here is a simplified version:

struct Item: Identifiable, Codable {
    let name: String
    let id = UUID().uuidString
}

I need to give users the option to assign each item to a container (which users can also create and manage).

struct Container {
    let name: String
}

So an item can be in zero or one containers and I will store arrays of all items and all containers. I need to be able to filter the displayed data based on individual containers.

My issue is how best to represent the relationship between the items and containers, and how I should keep track of this state.

I am unsure which of these options is best (or if an alternative might be better):

  1. Each item has a string property called container
  2. Each container struct has an array of items that it contains
  3. All data stored as an array property in a single struct with a separate array of containers and the ID of items they contain
  4. Some other way

I will be persisting the data locally and in iCloud using CloudKit.

Any advice on a good way to structure this would be appreciated.

   

I think you should explore the Core Data route and save data this way. You can easily connect items to containers with relationships and storing in iCloud is also quite simple https://developer.apple.com/videos/play/wwdc2019/202/

1      

@nemecek-filip Thanks! So far I have just been using Codable. I will look at Core Data. I admit I have felt daunted by it so far

   

Core Data is definitely complex. If you never used it, I would recommend first following a few tutorial projects with Core Data before integrating it into your project.

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.

Try it for free

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.