Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I initialize the @State variable in the init function in SwiftUI?

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!

like image 639
norains Avatar asked Nov 07 '19 23:11

norains


People also ask

What does @state do in SwiftUI?

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.

Do you have to initialize variables in Swift?

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.

What does init do in SwiftUI?

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.

How do you initialize a class in Swift?

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


1 Answers

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!")     } } 
like image 87
GuillermoMP Avatar answered Sep 19 '22 16:09

GuillermoMP