Inserting integer into array in swift

江枫思渺然 提交于 2019-12-18 09:43:18

问题


I'm not really on point with Swift yet and there is a problem that is starting to be a tad annoying.

I just want to add integer in a double dimensional array but it is always returning the same error code : "fatal error : Array index out of range"

var arrayVolley = [[Int]]()

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

Here is where I try to insert :

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

And this is my main :

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

Thanks a lot for your help in advance


回答1:


Try to use append to add the integer to the array it is automatically the next idex. It think if the index was never used it gives an error e.g.

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 

or you intialize the array in the correct size, but it's need a size:

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]

It hope this helps you if not please feel free to comment.



来源:https://stackoverflow.com/questions/31797127/inserting-integer-into-array-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!