Search code examples
swiftnsnumber

Absorb value from NSNumber


let Rating = self.currentPerson.Rating // This is a NSNumber

Rating -= 1

What I'm trying to do, is to take an x value from the Rating, and then print the new value of Rating.

How do I do this properly?


Solution

  • To perform this operation in the way you wish you need to write your own function for handling it:

    infix operator -=
    
    func -=(lhs:inout NSNumber, rhs:Double) {
        lhs = NSNumber(value: lhs.doubleValue - rhs)
    }
    

    You also need to use a variable rather than a constant in your implementation:

    var Rating = self.currentPerson.Rating // This is a NSNumber
    
    Rating -= 1
    

    So that the value can be changed.