iOS Foundation(SwiftUI) Module 2- Lesson 8 challenge


Despite extensive brainstorming, I am unable to come up with a viable alternative to the solution provided.

Hey thanks for posting!

This is what I did:

/*
     Adds a pineapple to each of our pizzas. Changes the first property to this.
     */
    func addPineapple() {
        // Initialize an empty list of pizzas
        var updatedPizzas = [Pizza]()
        
        // Loop through our old list of pizzas to find their current toppings
        for pizza in pizzas {
            
            // Set a pizza we can change equal to the current pizza in the list
            var newPizza = pizza
            
            // Set this pizza's first topping to pineapple
            newPizza.topping1 = "Pineapple"
            
            // Add the updated pizza to our new list
            updatedPizzas.append(newPizza)
        }
        // Set the current pizzas to our new list, because we cannot directly change the current pizzas from here
        // Instead we need to set it to an entirely new list
        Pizza = updatedPizzas
        
    }

Also, I’d suggest not naming variables with capital letters, and giving the variable name some indication that it is a list. So perhaps renaming your Pizza to pizzaList, or just plural pizzas.

Here’s another pro tip, when posting code, use the tilde symbol, the weird squiggly looking symbol in the top-left of the keyboard ~. Then encapsulating your code within two tildes, so <code>.

1 Like

Your efforts are much appreciated. Can you please share whole ViewModel class code?

You’re welcome, and absolutely! I’ll do you one better than that. See here for the whole codebase: GitHub - agholson/Pizza-App

Cheers,
Andrew

P.S. spero che ti piace il mio umorismo

Here is what I did, that seems to work.

Comments please. It seems to work. I tried to to the change to the instantiated array in the View, but failed that. Decided to use a method in the class.

//
// PizzaPies.swift
// PizzaChallenge
//
// Created by Chris Percival on 3/19/22.
//

import Foundation

class pizzaMenu :ObservableObject{

@Published var pizzaPies = [Pizza()]


init(){
    //pizzaPies.append(Pizza(name:"Veggy",topping1: "Mushroom",topping2: "Onion",topping3: "Pepper"))
    pizzaPies[0] = (Pizza(name:"Veggy",topping1: "Mushroom",topping2: "Onion",topping3: "Pepper"))
    pizzaPies.append(Pizza(name:"Italian",topping1: "Salami",topping2: "Ham",topping3: "Onion"))
    pizzaPies.append(Pizza(name:"Greek",topping1: "Sausage",topping2: "Olive",topping3: "Onion"))
}

func changeToppings(){
    pizzaPies[0].topping1 = "Pineapple"
    pizzaPies[1].topping1 = "Pineapple"
    pizzaPies[2].topping1 = "Pineapple"
}

}

Also be sure to check the provided solution!

But like anything in programming, there’s more than one way to accomplish the same thing