App crashes when setting variable to nil

I have been experiencing a problem that I can't seem to figure out how it's happening or how to fix it.

When then view below appears, the app crashes and shows this message:
Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1a2120fac)

If I remove the line that sets color to nil the view appears without any crashes.

Code Block Swift
...
@Binding var color: Color?
var body: some View {
NavigationView { ... }
.onAppear {
switch background {
case .color:
color = nil // error not occurring when this line removed
...
}
}
}

I have looked up the error and worked out its about nil and optionals, but I don't know why setting the variable to nil doesn't work.

Has anyone got any ideas as to why this is happening and how to fix it?

Thanks is advance.
Answered by OOPer in 638598022
I cannot explain why, but if I replace lines 131 to 140 as follows, the error does not occur.
Code Block
ColorPicker("Change color", selection: Binding<Color> {
color ?? Color(.systemBackground)
} set: {
color = $0
})

Please try.
@BabyJ

Thanks for clarifying. Maybe you need to tap Save for step 5. Dismissing by swiping down does not cause the error.

Now I can examine what's going on behind.


When choosing the color the small preview doesn't change but the background does.

Surely. I will also check how Binding affects.
Accepted Answer
I cannot explain why, but if I replace lines 131 to 140 as follows, the error does not occur.
Code Block
ColorPicker("Change color", selection: Binding<Color> {
color ?? Color(.systemBackground)
} set: {
color = $0
})

Please try.
I can confirm that this doesn't show any errors and the ColorPicker works properly.

Thank you very very much @OOPer and @Claude31.
Sometimes a little rearranging does the trick.
App crashes when setting variable to nil
 
 
Q