How to convert textField.text value to Integer and sum two Integers

孤者浪人 提交于 2020-02-04 04:42:25

问题


Initialization of immutable value 'textfieldInt' was never used; consider replacing with assignment to '_' or removing it and textfield2Int

I get that warning twice for textfieldInt

This is all the code I have:

class ViewController: UIViewController {

    @IBOutlet weak var textField1: UITextField!
    @IBOutlet weak var textField2: UITextField!
    @IBOutlet weak var output: UILabel!

    @IBAction func calculate(_ sender: AnyObject) {
        let textfieldInt: Int? = Int(textField1.text!)
        let textfield2Int: Int? = Int(textField2.text!)
        let convert = textField1.text! + textField2.text!
        let convertText = String(convert)
        output.text = convertText

}

回答1:


You are receiving the warning because, as the warning tells you, you are instantiating textfieldInt and textfield2Int, but you're not using your created Integers textfieldInt and textfield2Int to be calculated as let convert, but you add the Strings textField1.text! and textField2.text! together...

I guess, you want your function to be that:

@IBAction func calculate(_ sender: AnyObject) {
    let textfieldInt: Int? = Int(textField1.text!)
    let textfield2Int: Int? = Int(textField2.text!)
    let convert = textfieldInt + textfield2Int
    let convertText = String(convert)
    output.text = convertText
}


来源:https://stackoverflow.com/questions/40109695/how-to-convert-textfield-text-value-to-integer-and-sum-two-integers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!