Shahar Melamed
Shahar Melamed

Reputation: 1734

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

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)
    }
}

Upvotes: 4

Views: 1657

Answers (2)

Daniel Messner
Daniel Messner

Reputation: 2567

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

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

Upvotes: 3

Liam
Liam

Reputation: 391

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

Upvotes: 1

Related Questions