简体   繁体   中英

Updating variables from one function inside another

I am trying to update the value of Int variables (that are from one function) inside of another function. What I have right now is two variables that are declared 0 outside of any functions. Then in one function, they are assigned a value of either 1 or 0. Up until this point everything is fine. Then I am trying to update the variables when the user taps a UIImageView (subtracting 3 from one variable and adding two to the other). The problem I am having is that instead of subtracting 3 and adding 2 to the 1 and 0, it is subtracting 3 and adding 2 to the original 0 that the variables were declared as.

var playerA:Int = 0
var playerB:Int = 0

func firstFunction(playerA:Int, playerB:Int) {
    if counter%2 {
        playerA = 1
        playerB = 0
    }
    else {
        playerA = 0
        playerB = 1
    }
}

func secondFunction(playerA:Int, playerB:Int) {
    counter += 1
    if counter%2 0 {
        playerA += -3
        playerB += 2
    }
    else {
        playerA += 2
        playerB += =3
    }

Here secondFunction returns -3 and 2 instead of -2 and 2.

My idea to fix this is to use an array that is returned from firstFunction , and to refer to the elements by index (like this ->[Int, Int] where the Ints are playerA and playerB ).

I'm going to assume there are some typo's in your code portion, so I've decided to fix them up so the functions are reflective of your write up. There's also no reason to pass in the arguments in this case:

var counter: Int = 0
var playerA: Int = 0
var playerB: Int = 0

func firstFunction() {
    if counter % 2 == 0 {
        playerA = 1
        playerB = 0
    }
    else 
    {
        playerA = 0
        playerB = 1
    }
}

func secondFunction() {
    counter += 1
    if counter % 2 == 0 {
        playerA -= 3
        playerB += 2
    }
    else 
    {
        playerA += 2
        playerB -= 3
    }
}

You should show us how you call your functions, but it is not going to work unless you declare the parameters as inout . Read up here to understand how it works (scroll down to In-Out Parameters), it comes with this example:

func swapTwoInts(inout a: Int, inout _ b: Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// Prints "someInt is now 107, and anotherInt is now 3"

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