1

In many cases in SwiftUI, values are marked with a $ to indicate that they’re a Binding variable, and allow them to update dynamically. Here’s an example of this behavior:

class Car: ObservableObject {
    @Published var isReadyForSale = true
}

struct SaleView: View {
    @Binding var isOn: Bool

    var body: some View {
        Toggle("Ready for Sale", isOn: $isOn)
    }
}

struct ContentView: View {
    @ObservedObject var car: Car

    var body: some View {
        Text("Details")
            .font(.headline)
        SaleView(isOn: $car.isReadyForSale)  // generates a Binding to 'isReadyForSale' property
    }
}

The $ is used twice to allow the Toggle to change whether the car is ready for sale, and for the car’s status to update the Toggle.

However, some values seem to update without the $. For instance, in this tutorial about different property wrappers, they show the following example:

class TestObject: ObservableObject {
    @Published var num: Int = 0
}

struct ContentView: View {
    @StateObject var stateObject = TestObject()
    
    var body: some View {
        VStack {
            Text("State object: \(stateObject.num)")
            Button("Increase state object", action: {
                stateObject.num += 1
                print("State object: \(stateObject.num)")
            })
        }
        .onChange(of: stateObject.num) { newStateObject in
            print("State: \(newStateObject)")
        }
    }
}

Why does it use Text("State object: \(stateObject.num)") and not Text("State object: \($stateObject.num)") with a dollar sign prefix? It was my understanding when you wanted a view to automatically update when a variable it uses changes, you prefix it with a dollar sign. Is that wrong?

Chris McElroy
  • 161
  • 11
Doug Smith
  • 29,668
  • 57
  • 204
  • 388
  • In your code, there is a comment giving a hint to the significance of the `$` -- it creates a Binding (eg a two-way communication) to the variable/property. That allows the receiver of the Binding to send an update that will propagate back up to the owner. Without the `$`, the receiver merely gets the value. In your first, example, for example, the `Text` doesn't need to update the value -- just receive it. – jnpdx Jan 03 '22 at 19:30
  • This is not a duplicate of https://stackoverflow.com/questions/56551131/what-does-the-dollar-sign-do-in-this-example. This is not just asking what $ does, but why it’s *not* being used in the first example, which is not obvious, and does not follow from the question marked as its duplicate. In this case, because TestObject is a StateObject, any changes to its Published variables force a reload of the view, including the TextView. This behavior isn’t obvious even if you understand what a Binding variable is. I have a fuller answer to this question that I’ll post if it’s reopened. – Chris McElroy Jan 03 '22 at 20:00

0 Answers0