What is @State in SwiftUI ?

The @State keyword is a @propertyWrapper, a feature just recently introduced in Swift 5.1 

  • State is a value or a set of values, that can change over time, and that affects a view’s behaviour, content, or layout. You use property with the @State attribute to add a state to a view.


  • when you initialize a property that's marked @State, you're not actually creating your own variable, but rather prompting SwiftUI to create "something" in the background that stores what you set and monitors it from now on! Your @State var just acts as a delegate to access this wrapper.

  • Every time your @State variable is writtenSwiftUI will know as it is monitoring it. It will also know whether the @State variable was read from the View's body. Using this information, it will be able to recompute any View having referenced a @State variable in its body after a change to this variable.

Code Example:-
  import SwiftUI
   
   struct ContentView: View {
       @State var counter = 0
       var body: some View {
           print("ContentView")
           return VStack {
               Button("Tap me!") { self.counter += 1 }
               LabelView(number: counter)
          }
     }
  }
//Label created   
  struct LabelView: View {
      let number: Int
      var body: some View {
          print("LabelView")
          return Group {
                  Text("You've tapped \(number) times")
          }
     }
  }





Comments

Popular posts from this blog

NSPredicate Cheatsheet, Basic, compound, Aggregate, String, comparison operators

what is appDelegate?

CRUD Operation Using RealmSwift database Part 1