WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

Project 11: Question on @Binding property wrapper

Forums > 100 Days of SwiftUI

I'm looking at Project 11's @Binding property wrapper and I have the following question:

In Project 2 Guess The Flag, when we attach alerts to a view, for example ZStack, we have

.alert(scoreTitle, isPresented: $showingScore) {...}

If we click isPresented and click Quick Help, we can see after isPresented it is a Binding object. However, when we declare showingScore, we wrote

@State private var showingScore = false //whether the alert is showing

This is declared as a @State property, instead of a @Binding property.

I believe this has something to do with what Paul says about a 2-way street?

My explanation is the following: In Project 11, when we declare

@State private var rememberMe = false

in struct ContentView, we tell SwiftUI to watch for this property's change locally. When we declare isOn as a Binding property, we tell SwiftUI that if isOn gets changed elsewhere, we want to reflect that change back to struct PushButton's isOn property, which has a @Binding property wrapper to establish that 2-way street.

   

When you have an @State variable that's a Bool, think of it as a simple light switch in a room.

@State private var lightSwitch = true  // the switch is either ON or OFF. It is the state of the room

Now think of a small light detector in the same room. You've programmed it as a separate struct. It might activate a desk fan if it detects light.

You could set the state of the light detector each time you flip the light switch in your room. But this is redundant work.

Instead, you can BIND the light detector's state to the room's lightSwitch variable. Then whenever the room's light switch is turned on, the light detector's state is activated, and the fan turns on.

But you might walk into a dark room and want the fan on! If the fan has its own switch, you can turn it on. However, since that state is BOUND to the room's light switch, when you turn the fan on, the room's light also is set to true.

NB: This doesn't read like a complete explanation. Let me have a think about this.

1      

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.