I would like to initialise the value of an @State
var in SwiftUI trough the init()
method of a Struct
, so it can take the proper text from a prepared dictionary for manipulation purposes in a TextField.
The source code looks like this:
struct StateFromOutside: View {
let list = [
"a": "Letter A",
"b": "Letter B",
// ...
]
@State var fullText: String = ""
init(letter: String) {
self.fullText = list[letter]!
}
var body: some View {
TextField($fullText)
}
}
Unfortunately the execution fails with the error Thread 1: Fatal error: Accessing State<String> outside View.body
How can I resolve the situation? Thank you very much in advance!
I would try to initialise it in
onAppear
.Or, even better, use a model object (a
BindableObject
linked to your view) and do all the initialisation and business logic there. Your view will update to reflect the changes automatically.SwiftUI doesn't allow you to change
@State
in the initializer but you can initialize it.Remove the default value and use
_fullText
to set@State
directly instead of going through the property wrapper accessor.