在swift中将整数插入数组

时间:2015-08-03 21:34:00

标签: arrays swift integer

我还没有真正意识到Swift,并且有一个问题开始变得有点烦人。

我只想在双维数组中添加整数,但它总是返回相同的错误代码:"致命错误:数组索引超出范围"

var arrayVolley = [[Int]]()

init(){
    self.arrayVolley = [[]]
}

这是我尝试插入的地方:

func addPoints(score : Int, x : Int, y : Int){

    if (score > 11 || score < 0){ //11 will be translated as 10x
        println("Error on score value")
    }
    else {
        if (x>6 || y>6){
            println("Out of array")
        }
        else{
            arrayVolley[x][y]=score
        }
    }
}

这是我的主要内容:

var i=0
var j=0
for i in 0...6 {
    for j in 0...6{
        println("Entrez le score")
        var scoreinput=input()
        var score = scoreinput.toInt()
        distance.addPoints(score!, x: i, y: j)
    }
}

非常感谢您的帮助

1 个答案:

答案 0 :(得分:0)

尝试使用append将整数添加到数组中,它自动成为下一个idex。它认为如果从未使用过该索引,则会出现错误,例如:

var test = [Int]()
test.append(2) // array is empty so 0 is added as index
test.append(4)
test.append(5) // 2 is added as max index array is not [2,4,5]
test[0] = 3 // works because the index 0 exist cause the where more then 1 element in array -> [3,4,5]
test[4] = 5 // does not work cause index for never added with append 

或者以正确的大小初始化数组,但它需要一个大小:

var test = [Int](count: 5, repeatedValue: 0) // [0,0,0,0,0]
test[0] = 3 //[3,0,0,0,0]
test[4] = 5 [3,0,0,0,5]

希望这对你有帮助,如果没有,请随时发表评论。