DEV Community

Oluwasanmi Aderibigbe
Oluwasanmi Aderibigbe

Posted on

Day 36 of 100 Days Of Swift UI

I just completed day 36 of Hacking with Swift's 100 days of Swift UI.

Today I learnt about a new type of swift UI property annotation called the Observedproperty. I also learnt about user defaults and the codable protocol.

So far we have been using the @State property to represent the states of our app. The @State works only with variables and structs. The reason why Structs work so well with the @State property is because Structs are constant. That means anytime a property of a struct changes its value, the struct is destroyed and created again. Whenever the struct is created again, the @State property is assigned a new struct and this causes SwiftUI to redraw the views on the screen.

Since Structs are value types. They can't be shared between views as each view would have its own copy of the struct.
For this, we have to use classes to model our states. But since classes are not constants we can't use the @State annotation with classes. This is because when properties of a class change their value the class is not destroyed and created again.

In order to use classes to model our states, we have to use a new kind of annotation called the Observedproperty

class User: ObservableObject {
    @Published var firstName = "James"
    @Published var lastName = "Bond"
    var age = 50
}
struct ContentView: View {
   @ObservedObject var user = User()

    var body: some View {
        VStack {
            Text("Your name is \(user.firstName) \(user.lastName).")

            TextField("First name", text: $user.firstName)
            TextField("Last name", text: $user.lastName)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The code above uses a class to model the state of a screen. In order to use classes to model the state of your screen, you need three things:

  • Your class must conform ObservableObject protocol.
  • You need to tell SwiftUI which properties of your class you want it to observe for changes. You do this with the @Published annotation. As you can see the age property of the User class isn't marked with the @Published annotation. That means whenever we change the value of the age property, SwiftUI will not redraw our views. We also need to annotate our class in the view with @ObservedObject

Top comments (0)