BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

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.

3      

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/

4      

@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

3      

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.

3      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.