Swift:如何在Label中显示Int?

Swift: How to display Int in Label?

我需要在 TableViewCell 标签中显示 Int 以获得值的总和。 这是我的代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "eventCell", for: indexPath) as! BudgetTableViewCell
    
    let budgetEvent: BudgetModel
    budgetEvent = budgetList[indexPath.row]
  
    cell.nameEventLabel.text = budgetEvent.eventName
    cell.spentBudgetLabel.text = String(budgetEvent.spentBudget!)
    
    
    let totalSpent = budgetList.map{ [=11=].spentBudget! }.reduce(0, +)
    print("sum \(totalSpent)")
    return cell
}

当我 运行 我的应用程序出现错误消息时:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

值为零。

您正试图强制展开您的值,这不是一个好的做法,就好像该值不存在一样,您的应用程序 fails/crashes。

强制展开意味着您使用 ! 运算符告诉编译器您确定有一个值,我们可以提取它。在以下几行中,您正在使用强制展开:

// 1
cell.spentBudgetLabel.text = String(budgetEvent.spentBudget!)
// 2
let totalSpent = budgetList.map{ [=10=].spentBudget! }.reduce(0, +)

很难判断是哪一个导致了您的错误,但您可以改进代码以帮助您识别问题:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "eventCell", for: indexPath) as! BudgetTableViewCell

    let budgetEvent = budgetList[indexPath.row]

    cell.nameEventLabel.text = budgetEvent.eventName
    if let spentBudget = budgetEvent.spentBudget {
        cell.spentBudgetLabel.text = String(spentBudget)
    } else {
        print("SpentBudget is empty")
    }

    let totalSpent = budgetList.compactMap{ [=11=].spentBudget }.reduce(0, +)
    print("sum \(totalSpent)")
    return cell
}

我用 compactMap 替换了 map 函数,这将 return 只有非可选值。你可以阅读这个 here

你可以这样使用,

cell.spentBudgetLabel.text = String(format: "%d", budgetEvent.spentBudget)