-1

Why can not access/set an empty array's first item by subscript?

eg:

var array: [Int] = []
array[0] = 1 //fatal error: Index out of range
邓利文
  • 1
  • 2

4 Answers4

1

By var array: [Int] = [] you create empty array, so it doesn't have values with index 0.

To fix that you can append to the array like:

array.append(1)
print(array[0]) // 1

or set the array of values to your empty array:

array = [1] // another way to do that: "array += [1]"
print(array[0]) // 1

or predefine array filled with any values (0 for example):

let n = 10
array = Array(repeating: 0, count: 10)
array[0] = 0
pacification
  • 5,838
  • 4
  • 29
  • 51
0

Empty array initialization is fine. Than if you want to acces/set first item you just have to make:

array.append(1) 

and it will be stored at index 0 at first and you can access it easily: array[0] - but that access is just to read not to add. To add value you have to make 'append'. But if array is not empty than you can CHANGE that value by making:

array[0] = 7

However if you still want to add value at specified index, you could use:

array.insert(1, at: 0) //value at index
M. Wojcik
  • 2,301
  • 3
  • 23
  • 31
0

The index is out of range because there are no elements in the array, so there is no index 0. To add an element to an array, you have to do

array.append(1)

After the above line, you can set the first element:

array[0] = 2

because there is an element in the array now.

Only use the subscript when you are sure that the index exists in the array.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

Try,

array.append(1)

or

array.insert(1, at: 0)

or

array = [1]
Abirami Bala
  • 760
  • 1
  • 10
  • 25