-1

Help. I just converted to swift 3 and am getting errors when I try to add two NSNumbers together i.e.:

var foodPrice: NSNumber!
var priceSum: NSNumber!
foodPrice = 6.79
priceSum = 11.89
var totalSum = NSNumber(foodPrice + priceSum) // <-- error here

OR

var totalSum = (foodPrice + priceSum) as NSNumber // <-- still error here

Doesn't matter how I change totalSum I can't get away from this error. Please help. This is my official SOS. Dazed and confused here. How do I make this work?

JAL
  • 41,701
  • 23
  • 172
  • 300
David Villegas
  • 458
  • 3
  • 18

3 Answers3

1

Why not write your own + override for NSNumber?

func + (lhs: NSNumber, rhs: NSNumber) -> NSNumber {
    return NSNumber(value: lhs.floatValue + rhs.floatValue)
}

var foodPrice: NSNumber = 6.79
var priceSum: NSNumber  = 11.89

var totalSum = foodPrice + priceSum // 18.68

I use floats here but you can use any type you need.

JAL
  • 41,701
  • 23
  • 172
  • 300
  • 1
    The problem that I see is: What is *"any type you need"*? The application might use NSNumbers containing (for example) Float, Double, and (U)Int64 at different places. No matter which representation you use in your `+` operator, it won't work correctly in all cases. – Martin R Oct 04 '16 at 07:58
  • @MartinR Your right, this isn't really a reusable approach. Any suggestions how to improve this function (if any)? Or just treat each NSNumber on a case by case basis. – JAL Oct 04 '16 at 18:33
0
var foodPrice: NSNumber!
var priceSum: NSNumber!
foodPrice = 6.79
priceSum = 11.89
var totalSum = NSNumber(double: foodPrice.doubleValue + priceSum.doubleValue)

Try this out..!

user3608500
  • 835
  • 4
  • 10
0

Try

var totalSum = NSNumber(value: foodPrice.doubleValue + priceSum.doubleValue)
Avt
  • 16,927
  • 4
  • 52
  • 72