Search code examples
swiftsubscript

Swift: Can not access/set an empty array's first item by subscript


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

Solution

  • 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