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

Edutainment Challenge: Passing Data between Views

Forums > 100 Days of SwiftUI

I'm trying to approach this project by creating two custom views: one for the settings and the other for the game. That being said, I've got to juggle between ContentView, Game, and Settings, and I don't know how to pass the data back and forth between these (to do things like keep a score, etc.). I've got a State variable in my ContentView that keeps track of a score, and I'd like for Game to be able to add to that, and I want Settings to be able to set it back to zero. How would I go about doing this?

3      

Without giving too much away, have a look at this article from Paul. I would say using EnvironmentObject would best suit your circumstances and this article will explain to you what to do.

https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views

Dave

4      

edutainment is challenge right before introduction of switching between views. so i think it should be done using everything you learned before day 36.

3      

This answer might be coming in a bit late, $ essentiall means it's a Binding that wraps around a certain value.

Binding(
   get: { return x }
   set: { x = $0 }
)

by definition, we can then pass these values as Binding<Type> and store them. This will then create a 2 way binding on every view holding this value.

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.