Bryan Cimo Bryan Cimo - 5 months ago 13
Swift Question

Swift convert object that is NSNumber to Double

I have this code in Swift and it works, but I would think there is a better way to get my object from NSNumber and convert it to a Double:

var rating: NSNumber
var ratingDouble: Double

rating = self.prodResult?.prodsInfo.prodList[indexPath.row].avgRating as NSNumber!!

ratingDouble = Double(rating.doubleValue)

Answer

There are several things you can do:

var ratingDouble:Double

ratingDouble = rating as Double   // 1
ratingDouble = Double(rating)     // 2
ratingDouble = rating.doubleValue // 3
  1. The first item takes advantage of Objective-Cbridging which allows AnyObject and NSNumber to be cast as Double|Float|Int|UInt|Bool.
  2. The second item presumably goes through a constructor with the signature init(_ number: NSNumber). I couldn't find it in the module or docs but passing AnyObject in generated an error that it cannot be implicitly downcast to NSNumber so it must be there and not just bridging.
  3. The third item doesn't employ language features in the same way. It just takes advantage of the fact that doubleValue returns a Double.

One benefit of 1 is that it also works for AnyObject so your code could be:

let ratingDouble = self.prodResult!.prodsInfo.prodList[indexPath.row].avgRating! as Double

Note that I removed the ? from your function and moved the ! in. Whenever you use ! you are eschewing the safety of ? so there's no reason to do both together.

Comments