将整数插入 swift 中的数组
Inserting integer into array in swift
我还没有真正理解 Swift,并且有一个问题开始变得有点烦人。
我只想在二维数组中添加整数,但它总是返回相同的错误代码:"fatal error : Array index out of range"
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)
}
}
非常感谢您的提前帮助
尝试使用 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]
希望对您有所帮助,如有不便请随时评论。
我还没有真正理解 Swift,并且有一个问题开始变得有点烦人。
我只想在二维数组中添加整数,但它总是返回相同的错误代码:"fatal error : Array index out of range"
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)
}
}
非常感谢您的提前帮助
尝试使用 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]
希望对您有所帮助,如有不便请随时评论。