rincdani923
rincdani923

Reputation: 59

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

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

}

Upvotes: 3

Views: 26301

Answers (1)

David Seek
David Seek

Reputation: 17152

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
}

Upvotes: 11

Related Questions