Monday, June 16, 2025

@State Vs Binding

@State Vs Binding 


Sakshi! Let's clarify what @Binding does and why it's different from a normal variable or @State in SwiftUI.


๐Ÿ” What is @Binding?

@Binding is a way for a child view to read and write a value that is owned by its parent.

It's like saying:

“I don’t own this value, but I want to access and change it directly from my parent.”


๐Ÿง  Difference Between @State and @Binding

Property WrapperOwnershipCan Modify State?Use Case
@StateOwned by this view✅ YesWhen this view controls the state
@BindingOwned by parent✅ Yes (through parent)When this view uses or modifies state passed down from parent

๐Ÿงฉ In Your Case:

✅ You used:

swift
struct imageProfile: View { @Binding var isSelected: Bool ... }

This means imageProfile doesn't own isSelected, but gets it from Home like this:

swift
imageProfile(isSelected: $isImageChanged)

This lets the imageProfile:

  • Show different images based on the parent’s state.

  • Change that state if needed (e.g., on tap).


๐Ÿ” Without @Binding, like this:

swift
struct imageProfile: View { var isSelected: Bool // Not a binding }
  • It can read the value, but not update it.

  • Useful for display-only views, not interactive ones.


๐Ÿงช Example Summary

With @Binding:

swift
@Binding var isSelected: Bool // shared from parent isSelected.toggle() // updates parent's value

With @State:

swift
@State private var isSelected: Bool = false // independent local state

Let me know if you want a visual example like toggling checkmarks, radio buttons, etc., with multiple bindings!