简体   繁体   中英

Button in Xcode doesn't change a variable - Swift

I am trying to change the value of a variable in Xcode 7 with Swift. For some strange reason, it just doesn't work.

Here are the functions I used.

@IBAction func ten(sender: AnyObject) {
    var percentage = 0.10
    print("test")
}

@IBAction func twentyBtn(sender: AnyObject) {
    var percentage = 0.20
}

@IBAction func fifteenBtn(sender: AnyObject) {
    var percentage = 0.15
}

@IBAction func twentyfiveBtn(sender: AnyObject) {
    var percentage = 0.25
}

@IBAction func thirtyBtn(sender: AnyObject) {
    var percentage = 0.30
}

Then later in the code I use the percentage variable in this function.

@IBAction func calcTip(sender: AnyObject) {
    var billAmount: Int? {
        return Int(billField.text!)
        }

    var tipTotal = percentage * Double((billAmount)!)

    toalLabel.text = String(tipTotal)

    testLabel.text = String(percentage)

}

I don't understand why this shouldn't work because I also have this variable underneath my outlets where at the beggining of the code.

What's even more confusing is that if I try to see if it the button would print into the output, as you see I've tried for the one of the buttons, IT WORKS. Even trying to change the text within a label works, but for some strange reason it won't change a variable.

I'm not sure if this could be a bug with Xcode either.

Declare and initialize your percentage variable outside of your IBAction functions.

Like Mukesh already explained in the comments, if you are writing var percentage = 0.10 within one of these functions, you are not assigning 0.10 to the correct variable. Instead, you are creating a new variable within the scope of that function .

Any code written outside of that function cannot access it, and unless you are returning this value or passing it to a different function, the variable will be deleted by the garbage collector after the program finishes executing that function (so pretty much immediately).

Long story short, your code should look something like this instead:

var percentage = 0;

@IBAction func ten(sender: AnyObject) {
    percentage = 0.10
    print("test")
}

@IBAction func calcTip(sender: AnyObject) {
    var billAmount: Int? {
        return Int(billField.text!)
        }

    var tipTotal = percentage * Double((billAmount)!)

    toalLabel.text = String(tipTotal)

    testLabel.text = String(percentage)

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM