我有一个 tableView,它从 xib 文件加载单元格。单元格包含 2 个标签,第一个显示数量,第二个显示价格。数量是从静态模型中提取的并且工作得很好,价格是从模型中提取的,该模型是从 URLSession 的结果中填充的。下面是我的 cellForRowAt 函数,它在这种情况下运行良好:
if indexPath.section == 0 {
let item: BasketModel = cellItems[indexPath.row] as! BasketModel
let ordersCell = Bundle.main.loadNibNamed("OrderTableViewCell", owner: self, options: nil)?.first as! OrderTableViewCell
ordersCell.priceLabel.text = item.price
ordersCell.quantityLabel.text = String(basketStruct.getQty(id: item.id!))
return ordersCell
}
我的cell显示如下 Qty: 3 Price: 0.70
现在,我遇到的问题是,当我将价格标签设置为以下行时:
ordersCell.priceLabel.text = String(basketStruct.getQty(id: item.id!) * Int(item.price!)!)
我得到错误:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
我想要的是数量乘以价格。但是,当我尝试对任何东西使用 item.price 时,我必须强制打开它,然后我得到错误。
我该怎么做?
最佳答案
不是item.price
为nil,而是Int(item.price!)
为nil。
根据你的问题,你说显示的价格是 0.70
,所以我想 item.price
必须包含字符串 "0.70"
.
嗯,0.70
不是有效的 Int
,因此当您尝试将其解析为 Int
时,它的计算结果为 无
。
我想你的意思是 Double(item.price!)!
。
作为一个好习惯,您应该始终检查无效的数字字符串:
if let price = Double(item.price!) {
// ...
} else {
print("Invalid price: \(item.price!)")
}
关于Swift - 为什么我的应用程序在这种情况下发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48974499/