Search code examples
swiftif-statementcomparisoncounter

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


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")
    }
  }

Solution

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