xcodeswifterror-handlingfatal-errorskproduct

fatal error: unexpectedly found nil while unwrapping an Optional value in swift(SKProduct)


import UIKit
import SpriteKit
import StoreKit

extension SKProduct {
func localizedPrice() -> String {
    let formatter = NSNumberFormatter()
    formatter.numberStyle = .CurrencyStyle
    formatter.locale = self.priceLocale
    return formatter.stringFromNumber(self.price)!
}
}


class BuyCoin: SKScene {

var coin200a = SKProduct()

override func didMoveToView(view: SKView) {
NSLog("The price of this product is \(coin200a.localizedPrice())")
}
}

What am I doing wrong? PS: I am trying to get the local price of an in-app purchase product.


Solution

  • From DOCS price of SKProduct might be nil in case if SKProduct was not configured properly.

    var price: NSDecimalNumber! { get } // suppose crash happens here
    

    API demands from user to configure SKProduct with all proper values otherwise it will crash when you try to unwrap price that actually is nil


    For testing:

    I would write something like:

    if self.price != nil{ // we don't unwrap price (fetch optional)
       return formatter.stringFromNumber(self.price!)!
    } 
    else{
      return ""
    }