Property observers Swift 4

63 Views Asked by At
struct Kitchen // Coordinator 

{
   var foodItems = [FoodItem] () // Collection of FoodItem objects.
   var wastedItems = [WastedItem]() // Collection of WastedItem 
   var totalSpend = Double()
   var currentSpend = Double()
   var weeklyHouseholdFoodBudget = Double()
   var wastageCost = Double()

   init(aTotal:Double,aCurrent:Double,aBudget:Double,aWastage:Double)
    {
    self.totalSpend = aTotal
    self.currentSpend = aCurrent
    self.weeklyHouseholdFoodBudget = aBudget
    self.wastageCost = aWastage
    }

struct FoodItem : Equatable 
{
    var itemName = String()
    var itemQuantity = Double()
    var dateOfUse = String()
    var unitOfMeasurement = String()

    init(aName:String,aQuantity:Double,aDateOfUse:String,aUnit:String) 
    {
     self.itemName = aName
     self.itemQuantity = aQuantity
     self.dateOfUse = aDateOfUse
     self.unitOfMeasurement = aUnit
    }

   mutating func listFoodItems() 
     {
       for item in foodItems
       {
        print("Item Name:", item.getName(),",",
              "Qunatity:",item.getItemQuantity(),",", 
              "Unit:",item.getUnitOfMeasurement(),",",
              "Date of use:",item.getDateOfUse())
        }
      }

     mutating func removeFoodItem(aFood:FoodItem) 
      {
       if let anIndex = foodItems.index(of: aFood)
       {
       foodItems.remove(at: anIndex)
       print(aFood.getName(),"Has been removed")
       }
      }

      mutating func useFood(aFoodItem:inout  FoodItem,inputQty:Double) 

      {
        if (aFoodItem.getItemQuantity()) - (inputQty) <= 0
        {
         self.removeFoodItem(aFood: aFoodItem)
        }
         else
        {
         aFoodItem.useFoodItem(aQty: inputQty)                 
        }
      }

***Updated**** The issue I am having is when I use a func listFoodItems() the updated attribute itemQuantity does not change. I would like to know how to update the collection so when I call the func listFoodItems() it displays value changes.

The removal is ok, when the func runs the collection removes the object. The issue must be because I am using for item in foodItems to display, I need to reload it with updated values before I do this?

Thank you for any assistance.

1

There are 1 best solutions below

0
inokey On

Property observers are used on properties. The simplest example of a property observer.

class Foo {
    var bar: String = "Some String" {
        didSet {
            print("did set value", bar)
        }
    }
}

Now if you want to display some changes, you will need your own code in didSet method in order to do that. For example call reloadData().