Why does my tap counter go back to 1 when it gest higher than 10?

81 views Asked by At

I am trying to just simply have a button you tap and it adds 1 to a label. If that label is below 3 print its below three. If it's above 3 print that it's above. This works up until 10 which then prints out it's below three even though the label still shows 10 or higher.

var counter = 0
@IBOutlet weak var count: UILabel!

  @IBAction func testigbutton(_ sender: UIButton) {
      
       counter = counter + 1
       count.text = String(format: "%i", counter)
    
    if count.text! < "3" {
        
        print("Less than 3")
    } else if count.text! > "10" {
               
        print("More than 3")
    }
  }
3

There are 3 answers

0
Alejandro Iván On BEST ANSWER

Comparison of String is done character by character.

"9" is greater than "3" because the character 9 is above the character 3 if sorted.

"10" is less than "3" because, as this does character by character comparison, "1" is less than "3" and it finishes there.

If you need to do numerical comparison (an actual number instead of strings), use:

if Int(count.text!) < 3 { ... } else { ... }

Note that I'm comparing an actual Int and not a String.

0
Yonat On

Change the line

if count.text! < "3" {

to:

if counter < 3 {

This way you'll compare numbers by their order instead of strings by their lexicographic order.

0
JustSomeoneWhoCodes On

Since you are comparing a string, it checks each character. In other words, instead of comparing to 10, it compares to 1 then to 0. Since 1 is <3, it prints that. All you need to fix this is either to simply compare to your counter variable, or cast it to an Int or Double with something like Int(count.text!)