Inserting integer into array in swift

前端 未结 1 1886
名媛妹妹
名媛妹妹 2020-12-22 09:20

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 i

相关标签:
1条回答
  • 2020-12-22 09:33

    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.

    0 讨论(0)
提交回复
热议问题