简体   繁体   English

如何将字符串转换为 Int? Swift

[英]How to convert string to Int? Swift

I have this code, so I need how to convert spentBudget to Int?我有这段代码,所以我需要如何将花费预算转换为 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
}'''

String to int returns optional. String to int 返回可选。 For example:例如:

let myInt2 = Int(myString) ?? 0

For you example it will be:以您为例,它将是:

let spentBudgetInt = Int(spentBudget) ?? 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM