尝试重置时保留旧值的变量

时间:2015-05-26 20:42:14

标签: ios swift

我对Swift和编程都很陌生,所以这看起来非常基本,但是我在今天尝试解决这个问题的时候还没能在StackOverflow或Google上找到答案。

我为了娱乐而创建了一个基本的生活计数器应用程序,但是当我尝试重置用户的生命总数时,我遇到了一些麻烦。我能够从起始值中添加和减去总计,但是当我重置它时,初始值将保留在内存中。

例如,如果玩家1有9个生命而玩家2有0,如果我点击重置按钮,两个总数将显示10(默认值),但是,如果我从玩家1中减去1它将显示8并且如果我向玩家2添加1,它将显示1而不是11。

我想我需要以某种方式从reset中传递值,或者只是将默认变量放在其他地方?任何帮助表示赞赏。感谢。

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var playerOneAdd: UIButton!
@IBOutlet weak var playerOneMinus: UIButton!
@IBOutlet weak var playerOneLife: UILabel!
@IBOutlet weak var playerTwoMinus: UIButton!
@IBOutlet weak var playerTwoPlus: UIButton!
@IBOutlet weak var playerTwoLife: UILabel!
@IBOutlet weak var resetButton: UIButton!

var playerOne = 10
var playerTwo = 10

override func viewDidLoad() {
    super.viewDidLoad()

    playerOneLife.transform = CGAffineTransformMakeRotation(3.14)
}

@IBAction func PlayerOnePlusButton(sender: AnyObject) {
    ++playerOne
    playerOneLife.text = String(playerOne)
}

@IBAction func playerOneMinusButton(sender: AnyObject) {
    --playerOne
    playerOneLife.text = String(playerOne)
}

@IBAction func playerTwoMinusButton(sender: AnyObject) {
    --playerTwo
    playerTwoLife.text = String(playerTwo)
}

@IBAction func playerTwoPlusButton(sender: AnyObject) {
    ++playerTwo
    playerTwoLife.text = String(playerTwo)
}

@IBAction func resetPressed(sender: AnyObject) {
    var playerOne = 10
    var playerTwo = 10
    playerOneLife.text = String(playerOne)
    playerTwoLife.text = String(playerTwo)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

2 个答案:

答案 0 :(得分:1)

再次致电var时,您需要重新定义变量。你应该把它设置得相等。

playerOne = 10
playerTwo = 10

答案 1 :(得分:1)

您需要删除DISKPART> list volume Volume ### Ltr Label Fs Type Size Status Info ---------- --- ----------- ----- ---------- ------- --------- ------ Volume 0 E Backup NTFS Mirror 148 GB Healthy Volume 1 D DVD-ROM 0 B No Media Volume 2 L DVD-ROM 0 B No Media Volume 3 C OS NTFS Partition 223 GB Healthy System Volume 4 G Removable 0 B No Media Volume 5 H Removable 0 B No Media Volume 6 I Removable 0 B No Media Volume 7 J Removable 0 B No Media DISKPART> 中的var关键字:

resetPressed

@IBAction func resetPressed(sender: AnyObject) { playerOne = 10 playerTwo = 10 playerOneLife.text = String(playerOne) playerTwoLife.text = String(playerTwo) } 关键字定义了一个新变量。由于变量是在函数内部声明的,因此它们是局部变量,它们会覆盖实​​例变量。局部变量是函数的局部变量,因此在其他函数中不能访问被覆盖的变量。