๐Ÿ”ฐBinding from StateObject

SwiftUI โŸฉ Data Flow โŸฉ Binding โŸฉ create Binding from StateObject

๐Ÿ“— ๅƒ่€ƒ๏ผšSwiftOnTap โŸฉ Binding โญ๏ธ

// โญ๏ธ creating `Binding` from `@StateObject`
struct ExampleView: View {
    
    // โญ๏ธ `@StateObject` variable
    @StateObject private var viewModel = ExampleModel()

    var text: String {
        viewModel.isEnabled ? "Enabled" : "Disabled"
    }

    var body: some View {
        // โญ๏ธ $viewModel.isEnabled: Binding<Bool>
        // two-way connection to a source of truth
        //                 โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€ โญ๏ธ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
        Toggle(text, isOn: $viewModel.isEnabled)
    }
}

class ExampleModel: ObservableObject {
    // โญ๏ธ "published" source of truth:
    @Published var isEnabled: Bool = false
}

$viewModel.isEnabled and viewModel.$isEnabled are not equivalent. The former creates a Binding to isEnabled, whereas the latter unwraps the projected value of the @Published property wrapper wrapping isEnabled.

Last updated