matt2405 matt2405 - 4 months ago 35
Swift Question

Subtracting NSDecimalNumber swift?

I want to subtract one NSDecimalNumber from another simply. For whatever reason, this is not working, and the first NSDecimalNumber is not updating.

Here is my code.

func updateTotal(itemAmount amount: NSDecimalNumber) {
print("before: \(self.total), amount: \(amount)")
self.total.decimalNumberBySubtracting(amount)
print("after: \(self.total)")
}


Both self.total before and after are not affected by the subtraction. I am using swift 2.0

Answer

This is because decimalNumberBySubtracting(amount) returns a new value, which your code ignores:

let res = self.total.decimalNumberBySubtracting(amount)
print("after: \(res)")

If you would like to modify self.total, you can assign it back (assuming that it is a var)

self.total = self.total.decimalNumberBySubtracting(amount)