matt2405
matt2405

Reputation: 171

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

Upvotes: 2

Views: 478

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727087

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)

Upvotes: 6

Related Questions