Ios 如何将字符串转换为Int?敏捷的

Ios 如何将字符串转换为Int?敏捷的,ios,swift,string,integer,converters,Ios,Swift,String,Integer,Converters,我有这个代码,所以我需要如何将spentBudget转换为Int func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "eventCell", for: indexPath) as! BudgetTa

我有这个代码,所以我需要如何将spentBudget转换为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
}'''

字符串到int返回可选值。例如:

let myInt2 = Int(myString) ?? 0
例如,它将是:

let spentBudgetInt = Int(spentBudget) ?? 0

这回答了你的问题吗@JoakimDanielson谢谢你。第二条评论是正确的。我不建议使用.reduce0,+,我建议使用循环手册,因为您似乎不理解它。如果您想使用reduce,我将使用compactMap{Int$0.spendBudget}替换为compactMap{Int$0.spendBudget}。@Larme是的,这很有用。非常感谢。