Home > Net >  Swift, increment a number on each button tap
Swift, increment a number on each button tap

Time:12-18

I have created an app where I am uploading data to a database. However, I want to assign a specific key to each entry. For example, if the user is making their first entry into db. The key name would be "Entry 1", if they make a second entry, it would be "Entry 2". This is what I tried, but its not working.

@IBAction func doSomething(_ sender: Any) {
      var keyCounter = 0
      keyCounter = keyCounter   1
      print("Key Counter = ",keyCounter)
}

Here is the output of me pressing the button 3 times. Expected output: Key Counter = 3

Actual output:

enter image description here

I know that whenever I press the button its re-initializing the value of the counter to 0. I am not sure what the best way to approach this is. Any guidance or help would be appreciated.

CodePudding user response:

Do something like this:

class FooViewController: UIViewController {

  var keyCounter = 0

  @IBAction func doSomething(_ sender: Any) {
    keyCounter = keyCounter   1
    print("Key Counter = ",keyCounter)
  }
}
  • Related