Platform Specs:
- Xcode 16.2
- Swift 6.0.3
- iOS 18.2 + iOS Simulator 18.3.1
Issue:
Refer to the following code:
struct CustomView: View {
@Binding var prop: CustomStruct
init(prop p: Binding<CustomStruct>) {
_prop = p
}
init(isPreview: Bool) {
let p = CustomStruct()
_prop = .constant(p)
}
var body: some View {
VStack {
Text("hi")
}
}
}
#Preview {
CustomView(isPreview: true)
.preferredColorScheme(.dark)
}
The first constructor is for normal app functionality (and previews/functions correctly when used with the rest of the app in the ContentView preview tab). The second constructor is for previewing only CustomView
in its own preview tab. This constructor does not work when previewing in the same file, as shown above. It triggers an ambiguous crash, stating that the diagnostic log (which obviously provides no clear information) should be checked.
I have isolated the issue to be in the Binding reassignment in the second constructor. Replacing CustomStruct with anything but another struct, like an enum or primitive, fixes the issue.
Note: This bug only occurs when previewing (either through the #Preview macro or PreviewProvider struct).
This is not a bug. After extensive line-by-line and case-by-case testing, I realized I misunderstood how initializing default values in SwiftData works.
You can read more about the issue here:
- https://fatbobman.com/en/posts/relationships-in-swiftdata-changes-and-considerations/#the-misconception-of-setting-default-values-for-relationships