Changing an element
The elements of a Swift array can be replaced one at a time. Put the subscript, the array name with an index in square brackets, on the left of an assignment:
var ourArray = [50, 40, 30]
ourArray[0] = 15
ourArray[1] = -1
print(ourArray) // [15, -1, 30]
The array keeps its length. Each assignment overwrites the value stored at that index and leaves the other positions alone. Index 2 still holds 30.
Text works differently from arrays. A String can't be changed by writing to a position: s[0] = "j" is a compile error for a string s, because Swift strings don't take integer subscripts at all. An array has no such restriction.
The array must be a var
Assigning to an element changes the array, so the array has to be declared with var. With let, the compiler refuses:
let fruits = ["mango", "kiwi", "grapefruit"]
fruits[0] = "apple"
This reports cannot assign through subscript: 'fruits' is a 'let' constant. The fix is to declare fruits with var. The starter code of this lesson already does.
The new value must have the right type
An [Int] array stores only integers and a [String] array only strings. Assigning a different type is a compile error, such as cannot assign value of type 'String' to subscript of type 'Int'. Swift does not convert the value for you, and a[0] = 1.5 on an integer array fails in the same way.
Updating from the current value
The new value often depends on the old one. The compound assignment operators read the element, calculate, and store the result back in the same slot:
var ages = [14, 32, 50, 21]
ages[1] += 5 // same as ages[1] = ages[1] + 5
ages[3] -= 1
ages[0] *= 2
print(ages) // [28, 37, 50, 20]
The right-hand side can read other elements, for example ages[2] = ages[0] + ages[1].
Swapping two elements
Subscript assignment is also how you exchange two values. Keep one of them in a temporary constant first, or the first assignment would destroy it:
var a = [3, 1, 2]
let tmp = a[0]
a[0] = a[2]
a[2] = tmp
print(a) // [2, 1, 3]
Arrays also have swapAt(_:_:), which does the same in one call: a.swapAt(0, 1) turns [2, 1, 3] into [1, 2, 3].
Copies stay separate
Arrays are values in Swift. When you assign an array to another variable, or pass it to a function, the receiver gets its own copy, and changing an element of one doesn't change the other:
var original = [20, 37, 65, 28]
let copy = original
original[0] = 0
print(copy) // [20, 37, 65, 28]
print(original) // [0, 37, 65, 28]
The exercise, step by step
- Replace the first fruit. The first item is at index 0, so assign to
fruits[0]:fruits[0] = "apple". The array becomes["apple", "kiwi", "grapefruit"]. - Add 5 to the second age. The second item is at index 1. The statement
ages[1] += 5turns 32 into 37 and leaves the other ages as they were.
var fruits = ["mango", "kiwi", "grapefruit"]
var ages = [14, 32, 50, 21]
fruits[0] = "apple"
ages[1] += 5
These statements print nothing. To see the result, add print(fruits) and print(ages) afterwards. They show ["apple", "kiwi", "grapefruit"] and [14, 37, 50, 21].
Common mistakes
- Using
let. A constant array can't be edited, element by element or otherwise. - Using the wrong index.
ages[2] += 5changes the third age. Count from 0. - Writing
ages[1] = 5for "add 5". That replaces 32 with 5. Use+=to add to the existing value. - Assigning to an index that doesn't exist. Writing to an index outside the array crashes the program. A subscript can only replace an element that is already there; it never makes the array longer.
Key takeaways
- Replace an element with
array[index] = value, on avararray. - The value must have the array's element type.
+=,-=and*=update an element based on its current value.- Assigning an array makes an independent copy.
