Challenge - 5 Problems
Array Operations Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Swift code?
Consider the following Swift code that modifies an array. What will be printed?
Swift
var fruits = ["Apple", "Banana", "Cherry"] fruits.append("Date") fruits.insert("Elderberry", at: 1) print(fruits)
Attempts:
2 left
💡 Hint
Remember that insert(at:) adds the element at the specified index, shifting others to the right.
✗ Incorrect
The array starts as ["Apple", "Banana", "Cherry"]. append("Date") adds "Date" at the end. insert("Elderberry", at: 1) inserts "Elderberry" at index 1, pushing "Banana" and others right. So the final array is ["Apple", "Elderberry", "Banana", "Cherry", "Date"].
❓ Predict Output
intermediate2:00remaining
What happens after removing an element?
Given this Swift code, what will be the output?
Swift
var numbers = [10, 20, 30, 40, 50] numbers.remove(at: 2) print(numbers)
Attempts:
2 left
💡 Hint
Remember that remove(at:) removes the element at the given index and shifts the rest left.
✗ Incorrect
The element at index 2 is 30. Removing it leaves [10, 20, 40, 50].
🔧 Debug
advanced2:00remaining
Why does this Swift code cause a runtime error?
Examine the code below. Why does it crash when run?
Swift
var letters = ["a", "b", "c"] letters.remove(at: 3) print(letters)
Attempts:
2 left
💡 Hint
Check the valid indices for the array before removing.
✗ Incorrect
The array has indices 0, 1, 2. Trying to remove at index 3 causes a runtime 'index out of range' error.
❓ Predict Output
advanced2:00remaining
What is the final array after multiple operations?
What will be the output of this Swift code?
Swift
var colors = ["Red", "Green", "Blue"] colors.insert("Yellow", at: 0) colors.append("Purple") colors.remove(at: 2) print(colors)
Attempts:
2 left
💡 Hint
Track each operation step-by-step on the array.
✗ Incorrect
Start: ["Red", "Green", "Blue"]
Insert "Yellow" at 0: ["Yellow", "Red", "Green", "Blue"]
Append "Purple": ["Yellow", "Red", "Green", "Blue", "Purple"]
Remove at 2 ("Green"): ["Yellow", "Red", "Blue", "Purple"]
Option A matches this exactly.
So correct answer is B.
🧠 Conceptual
expert2:00remaining
How many elements remain after these operations?
Given this Swift code, how many elements are in the array after all operations?
Swift
var items = ["Pen", "Pencil", "Eraser", "Sharpener"] items.append("Marker") items.remove(at: 1) items.insert("Notebook", at: 2) items.removeLast()
Attempts:
2 left
💡 Hint
Count carefully after each operation.
✗ Incorrect
Start with 4 elements.
append("Marker") adds 1 → 5 elements.
remove(at: 1) removes 1 → 4 elements.
insert("Notebook", at: 2) adds 1 → 5 elements.
removeLast() removes 1 → 4 elements remain.