Swift中UITableView自定义cell的label展示Double值报错如何解决
问题排查与解决方案
报错原因分析
- 报错1:
initializer for conditional binding must have Optional type, not 'Double'
你的parts[indexPath.row].partCost本身就是非可选Double类型,if let只能用于解包可选类型,所以此处不需要用if let做条件绑定。 - 报错2:
Cannot assign value of type 'Double?' to type 'String?'Double()构造器返回的是Double?类型,而UILabel的text属性需要接收String?类型,你直接把Double值赋值给text属性,类型完全不匹配。 - 报错3:
No exact matches in call to initializer
else分支你直接把0.00这个Double字面量赋值给需要String类型的text属性,系统找不到匹配的赋值规则,所以触发该报错。
修复方案
如果你的partCost本身是Double类型,只需要将其格式化为指定样式的字符串即可,参考代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "DemoTableViewCell", for: indexPath) as! DemoTableViewCell cell.partNameLabel.text = parts[indexPath.row].partName // 直接将Double格式化为两位小数的字符串赋值给label let cost = parts[indexPath.row].partCost cell.partCostLabel.text = String(format: "%.2f", cost) cell.purchaseDateLabel.text = parts[indexPath.row].purchaseDate return cell }
如果你的partCost实际是String类型,需要先转Double再展示,修正逻辑如下:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "DemoTableViewCell", for: indexPath) as! DemoTableViewCell cell.partNameLabel.text = parts[indexPath.row].partName // partCost为字符串类型的转换逻辑 if let costDouble = Double(parts[indexPath.row].partCost) { cell.partCostLabel.text = String(format: "%.2f", costDouble) } else { cell.partCostLabel.text = "0.00" } cell.purchaseDateLabel.text = parts[indexPath.row].purchaseDate return cell }
内容的提问来源于stack exchange,提问作者Kiarra J.
相关产品推荐
相关产品推荐

