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

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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.