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)
There are several things you can do:
var ratingDouble:Double ratingDouble = rating as Double // 1 ratingDouble = Double(rating) // 2 ratingDouble = rating.doubleValue // 3
Objective-Cbridging which allows
NSNumberto be cast as
init(_ number: NSNumber). I couldn't find it in the module or docs but passing
AnyObjectin generated an error that it cannot be implicitly downcast to
NSNumberso it must be there and not just bridging.
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.