Search code examples
swiftoverridingswift4constantsvar

how to get label to constantly display int (swift4)


I am wondering if there is a way to get the label to display what the int. Basically overriding all of the if statements. I know I can do this witch if statements but I am just asking this question to see if i can write more efficient code.

class ViewController: UIViewController {
    var time = -3
    @IBOutlet var label: UILabel!

    @IBAction func method2() {
        time += 1
        label.text = String(time)
    }

    @IBAction func method1() {
        time += 1
        label.text = String(time)
    }
}

You see in this code that label.text = String(time) is repeated twice. I am trying to see if I can write this code so that it only appears once.


Solution

  • There are several ways you can do this, you can create an additional method, like so:

    class ViewController: UIViewController {
    
        var time = -3
    
        @IBOutlet var label: UILabel!
    
        @IBAction func method1() {
            self.incrementAndDisplayTime()
        }
    
        @IBAction func method2() {
            self.incrementAndDisplayTime()
        }
    
        private func incrementAndDisplayTime() {
            self.time += 1
            label.text = String(time)
        }
    }
    

    Or show time whenever time is set:

    class ViewController: UIViewController {
    
        var time = -3 {
            didSet {
                self.label.text = String(time)
            }
        }
    
        @IBOutlet var label: UILabel!
    
        @IBAction func method1() {
            self.time += 1
        }
    
        @IBAction func method2() {
            self.time += 1
        }
    
    }
    

    Or call one method from another:

    class ViewController: UIViewController {
        var time = -3
        @IBOutlet var label: UILabel!
    
        @IBAction func method1() {
            self.method2()
        }
    
        @IBAction func method2() {
            time += 1
            label.text = String(time)
        }
    }