Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Array Subscripts in Swift
Written by Team Kodeco

An array subscript is a way to access and modify elements in an array using the array’s index. The syntax for accessing an element using a subscript is array[index]. For example, the following code creates an array of integers and accesses the first element using a subscript:

var numbers = [1, 2, 3, 4, 5]
print(numbers[0]) // Output: 1

You can also use a subscript to modify the value of an element in an array. The following code modifies the first element of the numbers array to be 10:

numbers[0] = 10
print(numbers) // Output: [10, 2, 3, 4, 5]

You can also use a range of index in subscript to extract a subarray from the original array

let subArray = numbers[1...3]
print(subArray) // Output: [2,3,4]

It’s important to note that if you try to access an index that is out of range it’ll trigger a runtime error:

let lookupIndex = 999
let lookupValue = numbers[lookupIndex] // Fatal error: Index out of range

To avoid this, you can use the indices property of an array to see if the index you are looking for is within the array:

if numbers.indices.contains(lookupIndex) {
  let lookupValue = numbers[lookupIndex]
  print(lookupValue)
} else {
  print("Out of bounds!")
}
© 2024 Kodeco Inc.