【问题标题】:Inserting integer into array in swift快速将整数插入数组
【发布时间】:2015-08-03 21:33:59
【问题描述】:

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

非常感谢您提前提供的帮助

【问题讨论】:

  • 为什么会有var i = 0var j = 0?我认为您可以删除这些。另外,我认为在您的 init() 函数中设置 self.arrayVolley = [[]] 是多余的

标签: arrays swift integer


【解决方案1】:

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

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]

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

【讨论】:

    猜你喜欢
    • 2018-06-02
    • 2017-07-17
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    相关资源
    最近更新 更多