Let's see the simple source code:
import SwiftUI struct MyView: View { @State var mapState: Int init(inputMapState: Int) { mapState = inputMapState //Error: 'self' used before all stored properties are initialized } //Error: Return from initializer without initializing all stored properties var body: some View { Text("Hello World!") } }
I need the init function here because I want to do some data loading here, but there is one problem, the @State
variable could not be initialize here! How could I do with that? Maybe it's a very simple question, but I don't know how to do. Thanks very much!
With @State, you tell SwiftUI that a view is now dependent on some state. If the state changes, so should the User Interface. It's a core principle of SwiftUI: data drives the UI.
All of a class's stored properties—including any properties the class inherits from its superclass—must be assigned an initial value during initialization. Swift defines two kinds of initializers for class types to help ensure all stored properties receive an initial value.
By default, SwiftUI assumes that you don't want to localize stored strings, but if you do, you can first create a localized string key from the value, and initialize the text view with that. Using a key as input triggers the init(_:tableName:bundle:comment:) method instead.
An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer. For example, class Wall { ... // create an initializer init() { // perform initialization ... } }
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!") } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With