-1

I currently have a label that displays the value of a database read. The database has the value as a string. Through viewWillAppear, the database is read and will display the correct value in the label. I also have a button that when pressed, should add 1 to the current label value. When the label value changes, it will send the current value to the database to store.

I have the label displaying correctly. I was able to add a 1 to the label but it added it onto the end of the number instead of adding the two together (ie. the value was 6, button pressed, value is now 61). The database read/write portion is working correctly. The only thing I cannot seem to understand is how to add the two numbers together. It seems like such a simple process but everything that I have tried does not work. Any help is greatly appreciated!

One example of code that I have used:

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
        var variable = String([])

@IBAction func addOnePressed(_ sender: UIButton) {
        var variable = Int(label.text!)!
        let number = 1
        if let result = variable += number { self.label.text = result }
Hamish
  • 78,605
  • 19
  • 187
  • 280
Palmeeze
  • 37
  • 1
  • 11

1 Answers1

0

The main issue is that the property variable is not equal to the local variable variable

I recommend to declare the property variable as Int, set the label in viewDidLoad and increment the property in addOnePressed

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    var variable = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        self.label.text = "\(variable)"
    }

    @IBAction func addOnePressed(_ sender: UIButton) {
        variable += 1
        self.label.text = "\(variable)"
    }
}

PS: The syntax String([]) is confusing. Actually it's simply an empty string ""

vadian
  • 274,689
  • 30
  • 353
  • 361