Search code examples
functionswiftif-statementuibuttonibaction

Ambiguous use of operator '!='?


I am trying to create an if else statement. If the randomNumber equals the text of a label, then I want to add 1 to the CorrectLabel. If they do not equal each other than I want to add 1 to the IncorrectLabel. Here is my code:

@IBAction func checkButton(sender: UIButton) {

    if ( "\(randomImageGeneratorNumber)" == "\(currentCountLabel.text)"){
        currectAmountCorrect += 1
        CorrectLabel.text = "\(currectAmountCorrect)"

    }else if ("\(randomImageGeneratorNumber)" != "\(currentCountLabel.text)"){
        currentAmountIncorrect += 1
        IncorrectLabel.text = "\(currentAmountIncorrect)"
    }
}

I am getting an error on the "else if" statement line saying "Ambiguous use of operator '!=' ". I am unsure of what this error means or how to fix it.

What does this error mean and how can it be fixed?


Solution

  • You shouldn't compare like that. Just use .toInt() to cast the labeltext to int and compare it like that:

    var currentCount = currentCountLabel.text?.toInt()
    if randomImageGeneratorNumber == currentCount {
        currectAmountCorrect += 1
        CorrectLabel.text = "\(currectAmountCorrect)"
    
    } else {
        currentAmountIncorrect += 1
        IncorrectLabel.text = "\(currentAmountIncorrect)"
    }
    

    There is no need to put your value into a "".