【问题标题】:Updating variables from one function inside another从一个函数中更新另一个函数中的变量
【发布时间】:2016-10-18 07:35:32
【问题描述】:

我正在尝试更新另一个函数内部的 Int 变量(来自一个函数)的值。我现在拥有的是在任何函数之外声明为 0 的两个变量。然后在一个函数中,它们被赋值为 1 或 0。直到此时一切都很好。然后我试图在用户点击UIImageView 时更新变量(从一个变量中减去 3 并在另一个变量中添加两个)。我遇到的问题是,不是减去 3 并将 2 添加到 1 和 0,而是减去 3 并将变量声明为的原始 0 加上 2。

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
    }

这里 secondFunction 返回 -3 和 2 而不是 -2 和 2。

解决这个问题的想法是使用从firstFunction 返回的数组,并按索引引用元素(例如->[Int, Int],其中 Ints 是 playerAplayerB)。

【问题讨论】:

  • 不要将变量传递给函数。它应该工作得更好。变量是全局的,它们在所有对象中都是可见的。

标签: arrays swift function return


【解决方案1】:

我将假设您的代码部分中有一些拼写错误,因此我决定修复它们,以便函数反映您的编写。在这种情况下也没有理由传递参数:

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
    }
}

【讨论】:

    【解决方案2】:

    您应该向我们展示您是如何调用函数的,但除非您将参数声明为inout,否则它不会起作用。 Read up here to understand how it works(向下滚动到 In-Out 参数),它带有这个示例:

    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"
    

    【讨论】:

    • @Riley 很高兴它成功了,您可以将我的答案标记为正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多