如何将字符串转换为 Int? Swift
How to convert string to Int? Swift
我有这段代码,所以我需要如何将 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{ [=11=].spentBudget }.reduce(0, +)
self.spentBudget.text = String("$ \(totalSpent)")
print("sum \(totalSpent)")
return cell
}'''
String to int returns 可选。例如:
let myInt2 = Int(myString) ?? 0
以您为例,它将是:
let spentBudgetInt = Int(spentBudget) ?? 0
我有这段代码,所以我需要如何将 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{ [=11=].spentBudget }.reduce(0, +)
self.spentBudget.text = String("$ \(totalSpent)")
print("sum \(totalSpent)")
return cell
}'''
String to int returns 可选。例如:
let myInt2 = Int(myString) ?? 0
以您为例,它将是:
let spentBudgetInt = Int(spentBudget) ?? 0