Subscript method
In Swift, you can access individual elements of an array using subscripting.
The syntax for array subscripting is as follows:
array[index]
where array is the name of the array, and index is the position of the element you want to access. The index starts at 0 for the first element in the array, and goes up to array.count - 1 for the last element in the array.
For example, suppose you have an array of integers:
let numbers = [1, 2, 3, 4, 5]
To access the first element of the array (which is 1), you would use the following code:
let firstNumber = numbers[0]
To access the third element of the array (which is 3), you would use the following code:
let thirdNumber = numbers[2]
You can also use array subscripting to modify the values of individual elements in the array. For example, to change the second element of the array to 10, you would use the following code:
numbers[1] = 10
This would modify the numbers array to be [1, 10, 3, 4, 5].
Comments
Post a Comment