Challenge solution for Beginning Swift 2 Part 8: Dictionaries

Hi Greg

the code provided in challenge is very confusing. can u pls explain with more comments as i am totally loat in the solution provided. pls find the code pasted below .can u please explain it with more comments or provide a simpler solution as it is very confusing for a beginner like me.

// Key = restaurant name, value = total
var totalsByRestaurant: [String: Double] = [:]

// loop through all restaurant bills
for bill in restaurantBills {
  if let thisTotal = totalsByRestaurant[] {
    // there's already a total for this restaurant!
    totalsByRestaurant[] = thisTotal + bill.totalBill + bill.calculateTip()
  } else {
    // this is the first time seeing this restaurant in the dictionary
    totalsByRestaurant[] = bill.totalBill + bill.calculateTip()

// show the results
for (restaurantName, total) in totalsByRestaurant {
  print("The total spent at \(restaurantName): $\(total)")

Well first he defines a dictionary where the key is a string and the value is a double.

Then for every object it finds in restaurantBills, which he calls bills, he creates a thisTotal and unwraps the restaurant’s bill using if-let. If he gets a restaurant name, it’s because it already exists, so he adds it’s existing bill to the new bill. If it doesn’t unwrap to anything, the restaurant doesnt have a bill so it just stores the newly created bill.

It’s kinda like using the MR and M+ on your calculator. If you have an existing bill onscreen, you hit M+ and it will add the new value to the existing value in memory. Otherwise it will simply store the new value to memory.