There are 7 ways to create a SwiftUI.Binding:
Each one is useful for very specific purposes. I find it very interesting they have so many different ways to create binding. It's good to know how to apply each.
I don't know how to use #2, 3, 5:
import SwiftUI
struct BindingInitStudy: View {
@State private var optionalNumber: Int? = 0
@State private var randomNumber = Int.random(in: 0...100)
@State private var isBig = true
var body: some View {
VStack {
Text("Demonstrate use cases of all the Binding.init's")
if let n = optionalNumber {
Text("Number: \(n)")
} else {
Text("Number: is nil")
}
// #1 `init?(_ base: Binding<Value?>)`
// from binding to optional value to binding of value:
if let bindingToInt = Binding($optionalNumber) {
// number is not nil
Stepper("Enter number", value: bindingToInt)
}
// #2: `init<V>(_ base: Binding<V>) where Value == V?`
// Creates a binding by projecting the base value to an optional value
// how to use?
// #3: `init<V>(_ base: Binding<V>) where Value == AnyHashable, V : Hashable`
// Creates a binding by projecting the base value to a hashable value.
// how to use?
// #4: `init(projectedValue: Binding<Value>)`
// Creates a binding from the value of another binding
// this is SE-0293 in action: it's using this Binding.init to create a @Binding property wrapper
// to pass in function parameter that's a property wrapper
Button("Random number: \(randomNumber)") {
randomizeMe($binding: $randomNumber)
}
// #5 `init(get: @escaping () -> Value, set: @escaping (Value, Transaction) -> Void)`
// how to use? what's Transaction?
// #6: `init(get: @escaping () -> Value, set: @escaping (Value) -> Void)`
// Manually create a Binding
let binding = Binding(get: { randomNumber }, set: { randomNumber = $0; isBig = $0 > 50 })
Button("Random number: isBig: \(isBig ? "Yes" : "No")") {
randomizeMe($binding: binding)
}
// #7 static func constant(_ value: Value) -> Binding<Value>
// Make a Binding to a constant value
Toggle("You cannot change this", isOn: .constant(true))
}
}
func randomizeMe(@Binding binding: Int) {
binding = Int.random(in: 0...100)
}
}
struct BindingInitStudy_Previews: PreviewProvider {
static var previews: some View {
BindingInitStudy()
}
}