How to remove optional value for int, double, float in Firestore?

Viewed 414

I'm trying to retrieve a number type/value for my Total from my firestore, so far my code has been working, its just showing "$optional value: 30" in place of price.text = "$\(product.price) where it should be showing "$30".

Ive used INT, FLOAT, & DOUBLE (whether it be ?/!) and still getting the same results in the label showing "$Optional value: 30"

I just want to get rid of the "optional value" in the pricelabel when using the simulator

import Foundation
import UIKit

class List {
    var id: String
    var name: String
    var price: Float!                                       

    init(id: String,
         name: String,
         price: Float!) {                                             

         self.id = id
         self.name = name
         self.price = price
     }

     convenience init(dictionary: [String : Any]) {
        let id = dictionary["id"] as? String ?? ""
        let name = dictionary["name"] as? String ?? ""
        let price =  dictionary["price"] as? Float               

        self.init(id: id,
                  name: name,
                  price: price)
    }

}

import UIKit
import Firebase

class ListCell: UITableViewCell {

    weak var list: List!

    @IBOutlet weak var productName: UILabel!
    @IBOutlet weak var price: UILabel!

    func configure(withList list: List) {
        productName.text = product.name
        price.text = "$\(product.price)"
    }
}
1 Answers

Declare price as non-optional

var price: Float 

...

init(id: String,
     name: String,
     storeName: String,
     brand: String,
     category: String,
     strain: String,
     price: Float) {    

and assign a default value like the other properties

let price =  dictionary["price"] as? Float ?? 0.0

To display the price value with maximum 2 fractional digits use a NumberFormatter

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
price.text = "$\(formatter.string(for: product.price)!)"

And don't misuse String(describing, it's redundant anyway as brand and name are strings

productName.text = "\(product.brand): \(product.name)"
Related