How could I initialize the @State variable in the init function in SwiftUI?
Solution 1:
Property wrappers are generating some code for you. What you need to know is the actual generated stored property is of the type of the wrapper, hence you need to use its constructors, and it is prefixed with a _
. In your case this means var _mapState: State<Int>
, so following your example:
import SwiftUI
struct MyView: View {
@State var mapState: Int
init(inputMapState: Int)
{
_mapState = /*State<Int>*/.init(initialValue: inputMapState)
}
var body: some View {
Text("Hello World!")
}
}
Solution 2:
We can inject the data that the view needs.
Used a model which has access to the data that you wanted. Make a map view and use that instance of it in your parent view. This will also help to unit test the model.
Used the property wrapper @Binding to pass the data from the parent view to MapView
and used _mapState
which holds the value of mapState.
struct Model {
//some data
}
struct MapView {
private let model: Model
@Binding var mapState: Int
init(model: Model, mapState: Binding<Int>) {
self.model = model
self._mapState = mapState
}
}
extension MapView: View {
var body: some View {
Text("Map Data")
}
}
Solution 3:
I think that it would better to initialize when you write the code, just like:
@State var mapState = 0
or, if you want to binding the value with another view, use @Binding
.
You have more information at https://www.hackingwithswift.com/quick-start/swiftui/what-is-the-binding-property-wrapper