Aiden R. Aiden R. - 20 days ago 8
Swift Question

How do you compare a textfield value inside the textfield?

I have recently been learning to code Swift, using xCode. I have created a simple storyboard and am trying to compare a textfield value, inside the textfield.

Here is my code:

var numberone = 0
var numbertwo = 0
var answerstring :String = ""
var answerint :Int = 0
var userInput :String = ""

@IBAction func userTextField(_ sender: UITextField) {

numberone = randomInt(min: 1, max: 9)
numbertwo = randomInt(min: 1, max: 9)
questionLabel.text = "\(numberone) + \(numbertwo)"
answerint = numberone + numbertwo
answerstring = "\(answerint)"
if userTextField.text! = "\(answerstring)" {
questionResponse.text! = "Correct!"
} else {
questionResponse.text! = "Incorrect. The answer was \(answerint)."
}


The error is on the userTextField.text!, and it says:

Value of type '(UITextField) -> ()' has no member 'text'

Answer

You are comparing userTextField which is the method name, it should be sender instead:

@IBAction func userTextField(_ sender: UITextField) {
    numberone = randomInt(min: 1, max: 9)
    numbertwo = randomInt(min: 1, max: 9)
    questionLabel.text = "\(numberone) + \(numbertwo)"
    answerint = numberone + numbertwo
    answerstring = "\(answerint)"
    // here is the change, 'sender' instead of 'userTextField':
    if  sender.text! = "\(answerstring)" {
        questionResponse.text! = "Correct!"
    } else {
        questionResponse.text! = "Incorrect. The answer was \(answerint)."
    }
}