'Is it possible for a Struct to share a property in an array that is in a data model class?

Introduction

I have two structs Project and Task. I store all my projects and tasks in their respective arrays in the ModelData class. The relationship between the two structs are as follows. A Project can have zero or more tasks and a Task can have zero or one project.

Problem

At the moment I have put an optional Project property in the Task struct. If I were to make a change to a project in the projects array, the tasks that are associated with that particular project would not have the updated project as it is passed by value.

Question

What would be the best design to follow so that the Task struct can store an associated project and if changes were made in the ModelData class, the project property of an associated task would receive the changes?

Code

struct Project: Identifiable {
    let id: UUID = UUID()
    var title: String = ""
}

struct Task: Identifiable {
    let id: UUID = UUID()
    var title: String = ""
    var completed: Bool = false
    var project: Project?
}

class ModelData: ObservableObject {
    @Published var tasks: [Task]
    @Published var projects: [Project]

    init() {
        tasks = Task.sampleData
        projects = Project.sampleData
    }

    func delete(_ task: Task) {
        tasks.removeAll { $0.id == task.id }
    }
}

Solutions

  1. I could make the Project struct a class so that it is passed by reference, ideally I would want to avoid this as I am unaware of whether this is unconventional in SwiftUI

  2. I could make the project property a UUID type so when it comes to fetching the associated tasks for a project I filter using the UUID of the project and I would not have to worry about syncing the changes between copies.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source