0

I am having trouble trying to add a number inputted in a text box to add itself.

I have created two outlets - one where to input the number and the second where the answer shows. I also created a outlet action for the button where to submit it.

Now when I input a number, since its a string its a string it just puts it together like this. Enter number 10, outcome is 1010.

It does not add itself. I want an outcome of 20.

@IBOutlet weak var inputField: UITextField!

@IBAction func addButton(sender: AnyObject) {

    addAnswerBox.text = inputField.text + inputField.text

}

@IBOutlet weak var addAnswerBox: UITextField!

}

rmaddy
  • 314,917
  • 42
  • 532
  • 579

2 Answers2

1

What you have to do is convert the string to an int. Once you do that, then you can get 10 + 10.

This is what I mean:

let a:Int? = inputField.text.toInt()
let b:Int? = inputField.text.toInt()

if a && b {
    var ans = a! + b!
    answerLabel.text = "Answer is \(ans)"
} else {
    answerLabel.text = "Input values are not numberic"
}
Horray
  • 693
  • 10
  • 25
0

You need to take the IntValue from the string.

addAnswerBox.text = "\(inputField.text.intValue + inputField.text.intValue)"
skittle
  • 248
  • 2
  • 9
  • Thanks for the help, I needed to make a class as add so that way I dont reference it a 0. Then I had to create a func that adds the results then call it back on the button. – user3659356 May 05 '15 at 02:10
  • Thank you for helping out, I needed to create a class, which I thought in the first place. Then create a function in that class that adds var then call it back to the function of the button. – user3659356 May 10 '15 at 18:52