How to fix Xcode error "Segmentation fault: 11" after adding didSet to @State var

Viewed 1548

I want to add a "didSet" function to a parameter of a SwiftUI's View struct, but every time I try to build the app I get the "Segmentation fault: 11" error.

I tried to rename the parameter, but nothing happened. I also tried to make it Optional but because it's a @State it didn't worked. What can I do?

@State var text: String {
    didSet {
        print(oldValue, text)
    }
}
2 Answers

Try adding a default value to your var, which is necessary when defining a @State var.

@State var text: String = "" {
    didSet {
        print(oldValue, text)
    }
}

I have this issue too, seems like a compiler bug or something. I have done some digging and found a bug raised by Apple which can be found here https://bugs.swift.org/browse/SR-10918

Instead of using didSet on a variable with a @State property wrapper you could have a view model that conforms to BindableObject (part of Combine) and use @ObjectBinding in your view so when anything within your view model is updated SwiftUI will update your UI

Here is a nice tutorial on how to do so...

https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-objectbinding-to-create-object-bindings

Related