Bigfoot11
Bigfoot11

Reputation: 921

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?

Upvotes: 0

Views: 484

Answers (2)

Christian
Christian

Reputation: 22343

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 "".

Upvotes: 1

kovpas
kovpas

Reputation: 9593

First of all, you don't need to make comparison twice. Your code looks like

if true {
...
} else if false {
...
}

And, yes, int comparison would be better:

if let textAmount = currentCountLabel.text where randomImageGeneratorNumber == textAmount.toInt() {
    currectAmountCorrect += 1
    CorrectLabel.text = "\(currectAmountCorrect)"
} else {
    currentAmountIncorrect += 1
    IncorrectLabel.text = "\(currentAmountIncorrect)"
}

Upvotes: 0

Related Questions