Lesson 21Collections
Arrays
Ordered Collections
Arrays store multiple values of the same type in an ordered list. They're one of the most commonly used data structures in programming!
Creating Arrays
With Values
[1, 2, 3]Empty Array
[Int]()Type Annotation
var arr: [String] = []Repeated Values
Array(repeating: 0, count: 5)Array Indexing
Index 0
Apple
Index 1
Banana
Index 2
Orange
Arrays start at index 0, not 1!
Common Operations
.append()Add to end
.insert(at:)Add at index
.remove(at:)Remove by index
.countNumber of items
.contains()Check if exists
.first/.lastSafe access
var vs let
var- Mutable array (can add/remove/change)let- Immutable array (fixed contents)
main.swift
// Creating arrays
var fruits = ["Apple", "Banana", "Orange"]
let numbers: [Int] = [1, 2, 3, 4, 5]
// Empty arrays
var emptyArray: [String] = []
var anotherEmpty = [Int]()
// Array with repeated values
var zeros = Array(repeating: 0, count: 5)
print(zeros) // [0, 0, 0, 0, 0]
// Accessing elements by index (0-based)
print(fruits[0]) // Apple (first)
print(fruits[1]) // Banana (second)
print(fruits[2]) // Orange (third)
// Safe access with first and last
print(fruits.first ?? "Empty") // Apple
print(fruits.last ?? "Empty") // Orange
// Array properties
print("Count: \(fruits.count)") // 3
print("Is empty: \(fruits.isEmpty)") // false
// Adding elements
fruits.append("Mango") // Add to end
fruits.insert("Grape", at: 0) // Add at index
fruits += ["Kiwi", "Peach"] // Add multiple
print(fruits)
// Modifying elements
fruits[0] = "Green Grape"
print(fruits[0]) // Green Grape
// Removing elements
let removed = fruits.remove(at: 0) // Remove by index
print("Removed: \(removed)")
fruits.removeLast() // Remove last
fruits.removeFirst() // Remove first
// fruits.removeAll() // Remove all
// Checking contents
print(fruits.contains("Apple")) // Check if exists
// Finding index
if let index = fruits.firstIndex(of: "Mango") {
print("Mango is at index \(index)")
}Try It Yourself!
Create an array of your favorite movies, add a new one, remove one you don't like, and print how many movies are in your list!