1

Learning SwiftUI and having some difficulty in understanding @State. For example in the code below, why don't we use State variable (that is with $ sign) with if statement? Why only as Toggle argument? How do we differentiate both the states?

import SwiftUI

struct ContentView: View {
    @State private var isFrown = true
    var body: some View {

       VStack
        {
        Text ("Check toggle state")
        Toggle(isOn: $isFrown) {
                Text("")
                    .padding()
            if isFrown {          //why not $isFrown here
            Text("")
            }
            else {
            Text("")
            }

        }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
A Abhishek
  • 77
  • 6
  • 2
    This is the best explanation that I could find: "When it comes to referring to some state – for example, telling a state property to change when a toggle switch changes – we can’t refer to the property directly. This is because Swift would think we’re referring to the value right now rather than saying “please watch this thing.” Fortunately, SwiftUI’s solution is to place a dollar sign before the property name, which lets us refer to the data itself rather than its current value." https://www.hackingwithswift.com/quick-start/swiftui/working-with-state – leopic Jan 06 '20 at 17:59

1 Answers1

3

@State is a property wrapper struct that just wraps any value to make sure your view will refresh or redraw whenever that value changes. (https://developer.apple.com/documentation/swiftui/state)

Using a $ dollar sign provides access to the projectedValue of the state struct, which in this case gives a Binding (https://developer.apple.com/documentation/swiftui/binding), best explained by the documentation:

Use a binding to create a two-way connection between a view and its underlying model. For example, you can create a binding between a Toggle and a Bool property of a State. Interacting with the toggle control changes the value of the Bool, and mutating the value of the Bool causes the toggle to update its presented state.

Seb Jachec
  • 3,003
  • 2
  • 30
  • 56