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

passing 2 arguements in swiftui

Forums > SwiftUI

hi, i've been trying to pass 2 arguments into a foreach array but i cant.

                ForEach(expenses.items) { item in
                    HStack {
                        VStack(alignment: .leading) {
                            Text(item.name)
                                .font(.headline)
                            Text(item.type)
                        }

                        Spacer()
                            .frame(height: 10)
                        Text(item.amount, format: .currency(code: settinggs.type))
                    }
                }

the settinggs.type is the part that is erroring - i don't know how to get it in scope @StateObject var settings = Settings() this is the same for the expenses part aswell. thanks!

1      

@obelix oh no i did that on purpose

1      

ForEach is like a For loop. All vars that are within scope of the View struct are within scope of the ForEach.

Assuming Settings is a type you defined somewhere else that the view will read but not write, you should define it within the view, above the body, as a var without a property wrapper prefix, and pass it into the view as a parameter when you instantiate the view. (SwiftUI will force you to add all vars defined withn a view as parameters when you instantiate a view.)

expenses is more complicated, depending on where you are defining it and what parts of your app need to modify it. You will want to study the parts of "100 Days of SwiftUI" related to property wrappers such as @State, @StateObject and @ObservableObject. Unfortunately, because the table of contents at https://www.hackingwithswift.com/100/swiftui does not have meaningful titles, I have no idea where to direct you.

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.