2

As seen in the handling user input tutorial.

struct LandmarkList: View {
    @State var showFavoritesOnly = true

    var body: some View {
        NavigationView {
            List {
                Toggle(isOn: $showFavoritesOnly) {
                    Text("Favorites only")
                }
   ...

What is the showFavoritesOnly / $showFavoritesOnly syntax ?

Is it something unique to Binding<T> or can we use it in our own code ?

tsp
  • 1,938
  • 18
  • 15
  • 1
    Read about it https://stackoverflow.com/questions/56438730/what-does-the-swiftui-state-keyword-do – visc Jun 04 '19 at 18:42

1 Answers1

2

@State is designed to be used as a binding for SwiftUI properties. Any access to it outside the body accessor of your View will crash with:

Thread 1: Fatal error: Accessing State<Bool> outside View.body

SwiftUI automatically tracks all the @State declarations and re-calculates the appropriate body whenever any of them change.

@State is implemented using the Swift 5.1 @propertyDelegate feature, which enables the storage behavior of properties to be customized.

marcprux
  • 9,845
  • 3
  • 55
  • 72
  • thanks for the info. I looked into it and seems that the $ syntax is available for any `@propertyDelegate`. It returns the object that stores the value – tsp Jun 04 '19 at 19:50
  • Since the body gets recalculated, why do you yse the $ syntax and not the value of the state property? Wouldn't that do the same? – J. Doe Jun 05 '19 at 08:15