array.insert不会保存元素

时间:2017-01-25 02:31:28

标签: ios arrays swift3

我是Swift的初学者,并将Tictactoe游戏作为练习的一部分。我试图创建一个包含9个元素的空数组,以便跟踪游戏结果。我使用.insert方法填充相应的元素。然而,每次玩家点击按钮时,阵列都不会保存以前的元素并从初始阵列继续更新自己。 (哦,天哪我写的东西很糟糕)

这是我的代码:

import UIKit

class ViewController: UIViewController {

    var cross = false



    @IBAction func buttonPressed(_ sender: UIButton) {

        var resultArray = [String!](repeating: nil, count:9)

        let button = sender

       var index = button.tag

        if cross{

            button.setImage(UIImage(named: "cross.png"), for: UIControlState.normal)

            resultArray.insert("cross", at: index)

            resultArray.remove(at: index+1)

            cross = false
        }

        else{

            button.setImage(UIImage(named: "nought.png"), for: UIControlState.normal)

            resultArray.insert("nought", at: index)

            resultArray.remove(at: index+1)

            cross = true
        }


        print(resultArray)


    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

And here is what I get when running the code

1 个答案:

答案 0 :(得分:0)

您正在按下每个按钮重置阵列,移动

var resultArray = [String!](repeating: nil, count:9)

不在函数中,因此它在类级别定义,因此每次都不会重置。