NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

How to create a static instance of an Element as a default value when using Core Data?

Forums > SwiftUI


When using Core Data, is there a way to create a static instance of an entity, for default values.

There are cases in which I feel the need to pass optional instances of an entity to a new view, which need to be unwrapped. This need arises especially when working with the new NavigationSplitView, because I need to pass an instance of an element to the detail view.

In NavigationSplitView, for navigation to the detail view, as far as I understand, one needs to create a @State variable for the selected instance of an object, and the type of this @State variable is an optional that needs unwrapping. I'd like to make the @State variable to be the type of the core data element.

In Content View:

@State selectedPersonEntity: PersonEntity?

Note: Where Person is the Core Data entity.

If not declared optional, the App file will ask you pass a default instance of Person. This is what I want created as some sort of Static value.

When passing to the Detail View, I can pass selectedPerson to a variable of type Person.

Thus far, I've managed to work with passing the Attributes of Person, and unwrapping them individually. But for entities with lots of attributes, it is quite tiresome to pass a dozen of attributes to a new view.

Any help would be appreciated! Thanks!


A CoreData entity is an ObservableObject. Therefore, you have to use @ObservedObject and not @State.

For creating a CoreData entity you have always to create it in a NSManagedObjectContext. While you could create a temporary object in CoreData I would strongly advise not to do this in this use case. Everytime the View is initiated a default object would be created and if you don't pay attention you could end up with a whole lot of default objects in your data. I don't think this is what you want.

You could try to create your default object in a child context of your managedObjectContext and replace you default object with your current object. I don't know if this is a reasonable way to go. I don't have experience with this.


In HWS+ Cleaning up Core Data which explains and make an example property. Think there may be a trail period that you use to check it out


Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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.