0
0
Swiftprogramming~10 mins

Array operations (append, insert, remove) in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Array operations (append, insert, remove)
Start with empty array
Append element
Array grows by 1 at end
Insert element at index
Shift elements right from index
Remove element at index
Shift elements left from index
Array updated with changes
End
This flow shows how an array starts empty, then elements are added at the end or inserted at a position, and elements can be removed by shifting others.
Execution Sample
Swift
var arr = [Int]()
arr.append(10)
arr.insert(5, at: 0)
arr.remove(at: 1)
print(arr)
This code creates an empty array, adds 10 at the end, inserts 5 at the start, removes the element at index 1, then prints the array.
Execution Table
StepOperationArray StateIndex/ValueAction
1Initialize[]-Create empty array
2Append[10]Value=10Add 10 at end
3Insert[5, 10]Value=5, Index=0Insert 5 at index 0, shift 10 right
4Remove[5]Index=1Remove element at index 1 (10), shift left
5Print[5]-Output final array
💡 All operations done, array is [5]
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
arr[][10][5, 10][5][5]
Key Moments - 3 Insights
Why does inserting at index 0 shift the existing elements?
Because arrays keep order, inserting at index 0 moves existing elements right to make space, as shown in step 3 of the execution_table.
What happens if we remove an element at an index?
The element at that index is removed and elements after it shift left to fill the gap, as seen in step 4 of the execution_table.
Why does append add the element at the end?
Append always adds to the end without shifting, growing the array size, shown in step 2 of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the array after step 3?
A[5]
B[10, 5]
C[5, 10]
D[10]
💡 Hint
Check the 'Array State' column at step 3 in the execution_table.
At which step does the array size decrease?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Look for the step where an element is removed in the execution_table.
If we insert at index 1 instead of 0 in step 3, what would the array be?
A[5, 10]
B[10, 5]
C[10, 5, 10]
D[10]
💡 Hint
Think about where the new element goes and how existing elements shift.
Concept Snapshot
Array operations in Swift:
- append(value): adds value at the end
- insert(value, at: index): adds value at index, shifts right
- remove(at: index): removes element at index, shifts left
Arrays keep order and size changes accordingly.
Full Transcript
We start with an empty array. Append adds an element at the end, growing the array. Insert adds an element at a specific index and shifts existing elements right to keep order. Remove deletes an element at an index and shifts elements left to fill the gap. The final array reflects all these changes.