Swift UI on iOS 14 not assigning new object to @State property

On iOS 13 I used to use optional @State properties to adapt views. In my case, the presented view would either create a new object (an assignment) if the state that is passed into it is nil, or edit the assignment if an assignment was passed in. This would be done in the action block of a Button and it worked beautifully.

On iOS 14 / Xcode 12 this no longer seems to work. Given the following code which creates a new assignment and passes it into the editor view when the user taps a "New Assignment" button, the value of assignment remains nil. Is anyone else experiencing similar behaviour?

Code Block Swift
struct ContentView: View {
@Environment(\.managedObjectContext) var context
@State var assignmentEditorIsPresented = false
@State var assignment: Assignment? = nil
var Body: some View {
[...]
Button("New Assignment", action: {
self.assignment = Assignment(context: context)
self.assignmentEditorIsPresented = true
})
.sheet(isPresented: assignmentEditorIsPresented) {
[...]
}
}
}

What's even weirder is that I tried adding a random piece of state, an Int, to this view and modifying it right before the assignment state (between lines 9 and 10) and it didn't change either.

Answered by Theohhno in 617350022
Seems at this point to be a bug with Xcode 12 and the new framework. I was able to work around the issue by displaying the value of assignment in a View. I added the following code between lines 8 and 9 which fixed the issue and had the value updating properly:

Code Block Swift
Text("\(assignment?.description ?? "")"
.hidden()

I've sent in a bug report (FB7823148) through Feedback Assistant.

Still actual. Workaround still works...

Still having this same issue!

Still having this issue on XCode Version 15.0 (15A240d)

Still having the same issue. Used the let _ = assignment?.description workaround for my project.

Add before .sheet modifier:

.onChange(of: assignment) { oldValue, newValue in

assignment = newValue

}

Swift UI on iOS 14 not assigning new object to @State property
 
 
Q