Modifying Arrays
Part of the Fundamentals section of Coddy's Swift journey — lesson 64 of 86.
Arrays become truly useful when you can change their contents. To modify an array, you must declare it with var instead of let.
You can change an existing element by assigning a new value to a specific index:
var colors = ["Red", "Green", "Blue"]
colors[1] = "Yellow"
print(colors) // ["Red", "Yellow", "Blue"]To add new elements, use the append method for a single item, or the += operator to add multiple items at once:
var numbers = [1, 2, 3]
numbers.append(4)
print(numbers) // [1, 2, 3, 4]
numbers += [5, 6]
print(numbers) // [1, 2, 3, 4, 5, 6]To insert an element at a specific position, use the insert method:
var fruits = ["Apple", "Orange"]
fruits.insert("Banana", at: 1)
print(fruits) // ["Apple", "Banana", "Orange"]To remove elements, use remove(at:) with the index you want to delete:
var items = ["A", "B", "C", "D"]
items.remove(at: 2)
print(items) // ["A", "B", "D"]Remember, when you remove an element, all subsequent elements shift down to fill the gap.
Challenge
EasyWrite a function modifyInventory that takes an array of items, a new item to add, and an index to remove, then returns the modified array.
Perform the following operations in order:
- Change the first element to
"Updated" - Append the new item to the end of the array
- Remove the element at the specified index
Parameters:
items([String]): The initial array of itemsnewItem(String): The item to appendremoveIndex(Int): The index of the element to remove (after appending)
Returns: The modified array after all operations ([String])
Example: If items is ["A", "B", "C"], newItem is "D", and removeIndex is 2, the function should:
- Change first element:
["Updated", "B", "C"] - Append "D":
["Updated", "B", "C", "D"] - Remove at index 2:
["Updated", "B", "D"]
Cheat sheet
Arrays declared with var can be modified, while arrays declared with let are immutable.
Change an element by assigning a new value to a specific index:
var colors = ["Red", "Green", "Blue"]
colors[1] = "Yellow" // ["Red", "Yellow", "Blue"]Add a single element with append:
var numbers = [1, 2, 3]
numbers.append(4) // [1, 2, 3, 4]Add multiple elements with +=:
numbers += [5, 6] // [1, 2, 3, 4, 5, 6]Insert an element at a specific position with insert(_:at:):
var fruits = ["Apple", "Orange"]
fruits.insert("Banana", at: 1) // ["Apple", "Banana", "Orange"]Remove an element at a specific index with remove(at:):
var items = ["A", "B", "C", "D"]
items.remove(at: 2) // ["A", "B", "D"]When an element is removed, all subsequent elements shift down to fill the gap.
Try it yourself
func modifyInventory(items: [String], newItem: String, removeIndex: Int) -> [String] {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input12Arrays Basics
Declaring An ArrayAccessing ElementsModifying ArraysArray MethodsRecap - Product ListRecap - Reversed ArrayTuples