【问题标题】:How to remove optional value for int, double, float in Firestore?如何在 Firestore 中删除 int、double、float 的可选值?
【发布时间】:2020-02-12 18:50:42
【问题描述】:

我正在尝试从我的 Firestore 中为我的 Total 检索一个数字类型/值,到目前为止,我的代码一直在工作,它只是显示“$ optional value: 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)"
    }
}

【问题讨论】:

    标签: ios json swift uitableview google-cloud-firestore


    【解决方案1】:

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

    【讨论】:

    • 它有效!但是我将如何删除其中的小数点,因为它现在显示“$ 30.0”
    • 您需要添加一个NumberFormatter
    • 我不想给你带来痛苦,但我还是有点新,因为我只做了大约 3 个月,但我将如何使用数字甲来做到这一点
    • 它再次给了我这个可选值:'(
    • 如果price 被声明为非可选的,这是不可能的
    猜你喜欢
    • 2017-07-26
    • 2019-03-27
    • 1970-01-01
    • 2011-01-24
    • 2017-03-04
    • 1970-01-01
    • 2013-09-25
    • 2021-11-24
    • 1970-01-01
    相关资源
    最近更新 更多