UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

2      

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.

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.