ios - 如何在 Firestore 中删除 int、double、float 的可选值?

标签 ios json swift uitableview google-cloud-firestore

我正在尝试从我的 Firestore 中检索我的总计的数字类型/值,到目前为止我的代码一直有效,它只是显示“$可选值:30”而不是 price.text = “$\(product.price) 应该显示“$30”。

我使用过 INT、FLOAT 和 DOUBLE(无论是?/!),但在显示“$Optional value: 30”的标签中仍然得到相同的结果

我只是想在使用模拟器时去掉价格标签中的“可选值”

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)"
    }
}

最佳答案

价格声明为非可选

var price: Float 

...

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

并像其他属性一样分配默认值

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

要显示最多 2 位小数位的价格值,请使用 NumberFormatter

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
price.text = "$\(formatter.string(for: product.price)!)"
<小时/>

并且不要滥用String(describing),它无论如何都是多余的,因为brandname字符串

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

关于ios - 如何在 Firestore 中删除 int、double、float 的可选值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58405693/

相关文章:

当 $.post 不起作用时,jQuery $.ajax 起作用

ruby - 遍历 JSON 响应 Facebook Graph

swift - 为什么 String.append 不适用于像 "foo\(bar)"这样的格式化字符串?

ios - 如何从 parentViewController 中的 childViewController 更改 UITextField 和 UISwitch 的值

ios - 如何检查设备是否通过airplay连接?

ios - Swift 4+SwiftyJson 自动从 JSON 转换/生成对象

ios - XCode 6.1 iOS提交

swift - TableView 选择存储到核心数据实体

ios - 提取 UI ImageView 坐标

ios - 使用 HTML 5 和 IOS 资源