title: Sum elements of an array of objects in a for loop in swift: Sum variable not retaining value?
body: <p>I wrote what I thought was a basic function to sum up values of an array and calculate an amount left in budget.  I use a for loop to sum the elements of an array, then subtract this value from the budget.  However, for some reason the value of sum updates properly in the for loop, but the sum value out of the for loop is always zero.  In the below the println "Sum in the loop" is correct, but the println "Sum is" always equals 0. dataModel.spendingDataDisplay is an array of objects. Thanks for any help. </p>
  
  <pre><code>func amountLeftToSpend ()-&gt;Double {
          var sum:Double = 0.0
          for spendingItem in dataModel.spendingDataDisplay {
              var sum = spendingItem.amountSpent + sum
              println("Spending Item .amountSpent\(spendingItem.amountSpent)")
              println("Sum in the loop is \(sum)")
          }
          println("Sum is \(sum)")
          let amountLeftInBudget = dataModel.settingsData.weeklyBudget - sum
          println("Amount Left in Budget is \(amountLeftInBudget)")
          return amountLeftInBudget
      }
  </code></pre>