2

I'm trying to build a little app in SwiftUI. It is supposed to show a list of items an maybe change those. However, I am not able to figure out, how the data flow works correctly, so that changes will be reflected in my list.

Let's say I have a class of Item like this:

class Item: Identifiable {
    let id = UUID()
    var name: String
    var dateCreated: Date
}

And this class has an initializer, that assigns each member a useful random value.

Now let's say I want to store a list of items in another class like this:

class ItemStore {
    var items = [Item]()
}

This item store is part of my SceneDelegate and is handed to the ContextView.

Now what I want to do is hand one element to another view (from the stack of a NavigationView), where it will be changed, but I don't know how to save the changes made so that they will be reflected in the list, that is shown in the ContextView. My idea is to make the item store an environment object. But what do I have to do within the item class and how do I have to pass the item to the other view, so that this works? I already tried something with the videos from Apple's WWDC, but the wrappers there are deprecated, so that didn't work.

Any help is appreciated. Thanks a lot!

1

1 Answer 1

1

The possible approach is to use ObservableObject (from Combine) for storage

class ItemStore: ObservableObject {
    @Published var items = [Item]()

   // ... other code 
}

class Item: ObservableObject, Identifiable {
    let id = UUID()
    @Published var name: String
    @Published var dateCreated: Date

   // ... other code 
}

and in dependent views

struct ItemStoreView: View {
   @ObservedObject var store: ItemStore
   // ... other code 
}

struct ItemView: View {
   @ObservedObject var item: Item
   // ... other code 
}
Sign up to request clarification or add additional context in comments.

1 Comment

If I would do it like that, what would be the right way to pass an item from ItemStoreView to ItemView, so that I can use a TextField (which needs a binding to a string) on the name member of Item?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.