1

So as of now, I have been able to use Environment objects for relatively simple things, such as User Profile and User Goals, where we only have one set of values for these Environment objects. However, I am fairly confused on how I could implement an Array of Environment Objects. For example I want to create a Environment Objects called AddedFoods, which has 4 attributes (takes 4 paramaters):

name
totalCals
totalProtein
totalFat
totalCarns

And I want this environment to be able to take a large quantity of these objects, so obviously it must be some sort of array, but I have no clue how to implement this in Swift as I am relatively new. Any help would be greatly appreciated!

UPDATE: This is what I have for my other environment objects which aren't an array:

import Foundation

class UserInfoModel: ObservableObject {
    
    
    struct UserInfo: Identifiable {
        var id = UUID()
        var firstName: String
        var height: Double
        var weight: Double
        var gender: String
        var age: Double
        var activityLevel: String
        var BMR: Double
        
        
    }
    
    struct DailyCalorieGoals: Identifiable{
        var id = UUID()
        var calorieGoal: Double
        var fatGoal: Double
        var proteinGoal: Double
        var carbGoal: Double

    }
    
    struct CurrentCalorieProgress: Identifiable{
        var id = UUID()
        var calorieProgress: Int
        var fatProgress: Int
        var carbProgress: Int
    }
    
    @Published var personUserInfo = UserInfo.init(firstName: "",  height: 0, weight: 0, gender: "", age: 0, activityLevel: "", BMR: 0)
    @Published var personDailyCalorieGoals = DailyCalorieGoals.init(calorieGoal: 2400, fatGoal: 40, proteinGoal: 0, carbGoal: 0)
    @Published var personCurrentCalorieProgress = CurrentCalorieProgress.init(calorieProgress: 0, fatProgress: 0, carbProgress: 0)
    
    
}
2
  • what have you tried so far? Any model design that you came up with? can you share that? Commented Mar 9, 2021 at 8:39
  • I've updated it to show how I was previously using environment objects for other parts of my project Commented Mar 9, 2021 at 8:49

1 Answer 1

3

.environmentObject takes in ObservableObject as parameter, so what you could do is create a variable in your observable class that holds array of your AddedFoods type objects. You don't need Array of EnvironmentObjects.

import SwiftUI

struct AddedFoods:Identifiable{
    var name : String = ""
    var totalCals:Int = 0
    var id = UUID().uuidString
   //Your other properties
}


class UserInfoModel: ObservableObject,Identifiable {
    
    @Published var foods : [AddedFoods]?
    
    var id = UUID().uuidString

    init() {
        dummyData()
    }
    
    func dummyData() {
        var obj:[AddedFoods] = []
        obj.append(AddedFoods(name: "foo", totalCals: 2))
        obj.append(AddedFoods(name: "foo1", totalCals: 2))
        obj.append(AddedFoods(name: "foo2", totalCals: 2))
        obj.append(AddedFoods(name: "foo3", totalCals: 2))
        foods = obj
    }
}

struct myView:View{
    @EnvironmentObject var getFood:UserInfoModel

    var unwrappedFoods:[AddedFoods]{
        getFood.foods ?? []
    }
    
    var body: some View{
        ForEach(unwrappedFoods) {obj in
            Text(obj.name)
        }
    }
}

@Main

import SwiftUI

@main
struct WaveViewApp: App {
    
    @StateObject var model : UserInfoModel
    
    init() {
        _model = StateObject(wrappedValue: UserInfoModel())
    }
    
    var body: some Scene {
        WindowGroup {
            myView()
                .environmentObject(model)
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Is there an alternative way of unwrapping the object inside the view class? For example Just getting all values inside UserInfoModel and the doing the ForEach(unwrappedFoods) in the view class? The comment was very helpful btw!
After following your implementation, how would I use this view inside a tab view which uses struct myView: View { ...... and then the view you have used?
@Matthew please post new question, if you have other queries.For your first comment what exactly do you mean? If you want to move that unwrap code outside, you can have it directly in model class also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.