History
Loading...
Loading...
September 7, 2025
@Binding with custom getters and setters to transform data between parent and child views. This lets you maintain different data types while keeping views synchronized: @Binding var displayText: String in child can connect to @State private var count: Int in parent through a computed binding.Using protocol-based delegation creates clear contracts between views, making communication patterns explicit and testable. The delegate pattern separates concerns by letting child views focus on UI while parents handle business logic.
protocol CounterDelegate {
func didUpdateCounter(_ value: Int)
func didReachLimit() -> Bool
}
struct CounterView: View {
@State private var count = 0
let delegate: CounterDelegate
var body: some View {
VStack {
Text("Count: \(count)")
Button("Increment") {
if !delegate.didReachLimit() {
count += 1
delegate.didUpdateCounter(count)
}
}
}
}
}
struct ParentView: View, CounterDelegate {
@State private var totalCount = 0
var body: some View {
CounterView(delegate: self)
}
func didUpdateCounter(_ value: Int) {
totalCount = value
}
func didReachLimit() -> Bool {
return totalCount >= 10
}
}This approach prevents tight coupling between views, makes code more maintainable, and enables easier unit testing since you can mock delegates. It also provides compile-time safety for view communication requirements and makes complex parent-child relationships more predictable.