SwiftUI Implicit Writes for Embedded Objects

Is there a way to access the $ implicit write with embedded objects?

For instance, this doesn’t work because an embedded object has to be marked as optional:

class Location: Object, ObjectKeyIdentifiable {
  @Persisted(primaryKey: true) var _id: = UUID()
  @Persisted var name: String = ""
  @Persisted var address: Address?

class Address: EmbeddedObject {
  @Persisted var address1: String = ""
  @Persisted var city: String = ""
  @Persisted var state: String = ""
  @Persisted var zip: String = ""

  TextField("Business name...", text: $business.name)
  TextField("Address...", text: $location.address.address1)
  TextField("City...", text: $location.address.city)
  TextField("State...", text: $location.address.state)
  TextField("Stage Zip Code...", text: $location.address.zip)

If I try to change the address to non-optional, that throws an error.

And I can’t find a way or an example on how to implicitly write these which makes me do a complicated dance where I load existing values into state variables and save on dismissal, which may never happen.

Any best practices here?

I don’t know your exact case so I can be wrong but here what you can try.
Declare @State var address: Address
On view render bind it to the location.address
If it’s nil – bind it to the temporary Address (just create it as non managed object)
Where required – save this temporary object to the target location.address

Let me know if it’s working for you

Interesting. Maybe some clarification from someone on the Realm team would be in order…

The documentation in one place states that // Embedded object properties must be marked optional but in the actual class reference EmbeddedObject it’s clearly not optional nor are it’s properties.

The github comments also show properties that are not optional but perhaps it’s because the Embedded Dog object is in a List?

1 Like

I did see that this works.

I actually just passed in the address from the parent view and then it works with the implicit writes.

But… just like the linked objects, it appears that this pops the view on every keystroke as I have also mentioned in this other post this morning.