我正在尝试使用委托将数据从文本字段传递回以前的控制器。当我尝试在此调用中分配 Int 值时,我陷入困境。这个问题相当容易,但是我找不到简单的解决方案。我一直在尝试使用应该保存此值的其他属性的不同方法,但没有成功。我必须与此预算金额文本有什么关系才能正确转换?
protocol BudgetDelegate: class {
func enteredBudgetData(info: String, info2: Int)
}
class AddBudgetViewController: UIViewController {
var budget: Budget?
weak var delegate: BudgetDelegate? = nil
@IBOutlet weak var budgetName: UITextField!
@IBOutlet weak var budgetAmount: UITextField!
//
@IBAction func saveContent(_ sender: UIButton) {
if ((budgetName.text?.isEmpty)! && (budgetAmount.text?.isEmpty)!) {
navigationController?.pop(animated: true)
} else {
-> delegate?.enteredBudgetData(info: budgetName.text!, info2: budgetAmount.text!)
navigationController?.pop(animated: true)
}
}
}
错误 无法将类型为"字符串"的值转换为预期的参数类型"Int"
协议方法的info2
参数是 Int
类型,但您传递的是budgetAmount.text!
这当然是一个String
。您需要通过Int
.
也许您需要将文本字段中的文本转换为Int
。
delegate?.enteredBudgetData(info: budgetName.text!, info2: Int(budgetAmount.text!) ?? 0)
顺便说一句 - 您正在对!
运算符进行几次可怕的使用。您应该花时间了解可选以及如何安全地使用。
因此,根据您的问题,您只想传递来自UITextField
的Int
数据。根据您的描述,您在委派方面没有任何问题。
将String
转换为Int
很容易:
例:
let num = "1"
if let intNum = Int(num) {
// There you have your Integer.
}