Reputation: 7937
I have this function in Swift 3:
if let rating = product.rating as? Float {
itemRating.update(rating) //sets item rating. Number of stars
}
where product.rating
is a NSDecimalNumber
coming from an Objective C function.
I am in the midst of converting everything to Swift.
Every time I call itemRating.update(rating)
it gives the notorious:
fatal error: unexpectedly found nil while unwrapping an Optional value
The only way I got it to work was by this ugly implementation:
if let rating = product.rating as Decimal?, let floatRating = rating as? Float {
itemRating.update(floatRating) //sets item rating. Number of stars
}
which always gives a warning:
Cast from 'Decimal' to unrelated type 'Float' always fails.
Every other way I tried fails with the above error.
Here is the definition for update()
:
- (void)updateRating:(float)inRating;
What is going on with this?
Upvotes: 0
Views: 354
Reputation: 285160
if product.rating
is really a NSDecimalNumber
(not (NS)Decimal
) instance just use optional binding to unwrap the optional then get the floatValue
since NSDecimalNumber
inherits from NSNumber
.
if let rating = product.rating {
itemRating.update(rating.floatValue)
}
Upvotes: 3