【问题标题】:How to convert string to Int? Swift如何将字符串转换为 Int?迅速
【发布时间】:2021-05-26 22:48:18
【问题描述】:

我有这段代码,所以我需要如何将花费预算转换为 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
    
    if let spent = budgetEvent.spentBudget{
        cell.spentBudgetLabel.text = spent
   }else{
        print("spent budget is empty")
    }
    
    let totalSpent = budgetList.compactMap{ $0.spentBudget }.reduce(0, +)
    self.spentBudget.text = String("$ \(totalSpent)")
    print("sum \(totalSpent)")
    return cell
}'''

【问题讨论】:

  • 这能回答你的问题吗? Converting String to Int while using reduce()
  • @JoakimDanielson 谢谢。第二条评论是正确的。
  • 我不建议使用.reduce(0, +),我建议您使用 for 循环手册,因为您似乎不理解它。如果你还想使用reduce(),我会用compactMap{ Int($0.spendBudget) } 替换compactMap{ $0.spentBudget}
  • @Larme 是的,这很有帮助。谢谢。

标签: ios swift string integer converters


【解决方案1】:

String 到 int 返回可选。例如:

let myInt2 = Int(myString) ?? 0

例如,它将是:

let spentBudgetInt = Int(spentBudget) ?? 0

【讨论】:

    猜你喜欢
    • 2015-11-13
    • 2015-03-17
    • 1970-01-01
    • 2015-11-12
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    相关资源
    最近更新 更多