我正在尝试从我的 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
),它无论如何都是多余的,因为brand
和name
是字符串
productName.text = "\(product.brand): \(product.name)"
关于ios - 如何在 Firestore 中删除 int、double、float 的可选值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58405693/