3

I'm building a budget app in Swift.

The NSDecimalNumber is first added to an array after an action (below).

Then the NSDecimalNumber is converted to CurrencyFormat for TableView, and appended to a separate string array.

How can I find the sum of the first NSDecimalNumbers array to create an Available Amount Label?

var adding: [NSDecimalNumber] = [5, 6, 5.55, 6.55, 1]

I tried this to convert the number into NSDecimal(addingAmount), and then append it to the above array (adding):

let addingAmount = NSDecimalNumber(string: textInput.text) / decimal100
    adding.append(addingAmount)
    println(adding)
    println(reduce(adding, 0, +)) // prints 15

Unfortunately, println(adding) works, but nothing is printed for the sum.

Any help would be appreciated, thanks.

2 Answers2

6

This is because there is no definition of the binary operator '+' for the NSDecimalNumber type. So once you manually define the operator, you can do it.

func +(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
    return lhs.decimalNumberByAdding(rhs)
}
findall
  • 2,176
  • 2
  • 17
  • 21
-3

If you just want the total sum of the first array then you can cast it to double and add them together with map and reduce.

var adding: [NSDecimalNumber] = [5, 6, 5.55, 6.55, 1]
let test = adding.map { Double($0) }.reduce(0, combine: +)
println(test) // prints out 24.1
Henny Lee
  • 2,970
  • 3
  • 20
  • 37
  • 1
    this will not preserve the floating point value of NSDecimalNumber and should be used with extreme caution. – Jerland2 Jan 21 '19 at 22:53