Swift: Swift Arrays Tutorial

An array is like a shopping list — every to-do item listed in order. This lesson covers the complete set of Swift array operations, from creation to CRUD, all in one place.

1. What You'll Learn


2. An E-commerce Developer's Real Story

(1) Pain: Shopping cart list management in chaos, data out of sync

Alice is building the shopping cart feature for an e-commerce app. The user — Charlie — adds 5 items, then removes 2 and changes quantities 3 times. At checkout she discovers: the cart total doesn't match the individual item prices!

SWIFT
// Alice's original "manual" approach
var cartItem1 = "Laptop"
var cartItem2 = "Mouse"
var cartItemPrice1 = 999.0
var cartItemPrice2 = 25.0
// By the time items piled up, she was lost...

Alice was managing 6 items with 12 separate variables. When she added a 7th item, she didn't even know what to name the variable anymore. Cart data scattered across 20+ variables — change one and forget another.

(2) The Array Solution

SWIFT
var cartItems = ["Laptop", "Mouse", "Keyboard"]
var cartPrices = [999.0, 25.0, 89.0]
cartItems.append("Monitor")
cartPrices.append(349.0)
cartItems.remove(at: 1)
cartPrices.remove(at: 1)
print("Cart: \(cartItems)")
print("Total: $\(cartPrices.reduce(0, +))")

(3) Result: Structured data, 90% fewer bugs

Metric Scattered Variables Array Management
Variable count 18 2
Adding an item Create 3 new variables 1 line of append
Data consistency Often out of sync Guaranteed sync
Bugs per week 3-5 0-1

3. Creating Arrays and Basic Properties

An array is an ordered collection of elements — all must be the same type.

100%
graph TB
    A[Array] --> B[Index 0]
    A --> C[Index 1]
    A --> D[Index 2]
    A --> E[Index ...]
    B --> F[Element]
    C --> F
    D --> F
    E --> F
Creation Method Example Notes
Literal [1, 2, 3] Most common
Type annotation Int Empty array
Repeated value Array(repeating: 0, count: 5) All zeros
From range Array(1...5) From a range

(1) Creating Arrays

SWIFT
// Method 1: literal
let numbers = [1, 2, 3, 4, 5]
// Method 2: empty array
var emptyArray: [String] = []
// Method 3: repeated value
let zeros = Array(repeating: 0, count: 3)
print(zeros)
// Method 4: from range
let rangeArray = Array(10...15)
print(rangeArray)

(2) Common Properties

SWIFT
let items = ["Apple", "Banana", "Orange"]
print("Count: \(items.count)")
print("Is empty: \(items.isEmpty)")
print("First: \(items.first ?? "None")")
print("Last: \(items.last ?? "None")")
print("Contains Apple: \(items.contains("Apple"))")

▶ Example: Warehouse Inventory Check

SWIFT
// ============================================
// Managing warehouse inventory with arrays
// ============================================
var inventory: [String] = []
if inventory.isEmpty {
    print("Warehouse is empty, adding stock...")
}
inventory.append("Laptop")
inventory.append("Mouse")
inventory.append("Keyboard")
inventory.append("Monitor")
print("Inventory has \(inventory.count) items")
print("Products: \(inventory.joined(separator: ", "))")
print("First item: \(inventory[0])")
print("Last item: \(inventory[inventory.count - 1])")

Output:

TEXT 📖 Display only
Warehouse is empty, adding stock...
Inventory has 4 items
Products: Laptop, Mouse, Keyboard, Monitor
First item: Laptop
Last item: Monitor

4. Array CRUD Operations

Arrays are mutable collections — you can add and remove elements at any position.

Operation Method Example
Append to end append(_:) array.append(4)
Insert at position insert(_:at:) array.insert(0, at: 0)
Remove at position remove(at:) array.remove(at: 2)
Remove last removeLast() array.removeLast()
Remove all removeAll() array.removeAll()
Modify element Subscript assignment array[1] = 100

(1) Adding and Inserting Elements

SWIFT
var tasks = ["Buy groceries", "Pay bills"]
// Append to end
tasks.append("Call doctor")
// Insert at specific position
tasks.insert("Check email", at: 0)
print(tasks)

(2) Removing and Modifying Elements

SWIFT
var scores = [88, 92, 75, 60, 95]
// Modify
scores[1] = 98
// Remove
let removed = scores.remove(at: 3)
print("Removed: \(removed)")
scores.removeLast()
scores.sort()
print(scores)

▶ Example: To-Do List Manager

SWIFT
// ============================================
// Simple to-do list with arrays
// ============================================
var todoList = ["Buy milk", "Walk dog", "Write report"]
// Add
todoList.append("Read book")
todoList.insert("Morning exercise", at: 0)
// Modify
todoList[2] = "Write weekly report"
// Remove
let completed = todoList.remove(at: 1)
print("Completed: \(completed)")
// Traverse
print("\n=== Today's Todo ===")
for (i, task) in todoList.enumerated() {
    print("\(i + 1). \(task)")
}
print("\nRemaining tasks: \(todoList.count)")

Output:

TEXT 📖 Display only
Completed: Walk dog

=== Today's Todo ===
1. Morning exercise
2. Buy milk
3. Write weekly report
4. Read book

Remaining tasks: 4

5. Array Traversal and Bulk Operations

Swift provides multiple ways to traverse arrays and practical bulk operation methods.

Traversal Method Syntax Use Case
Basic for item in array Only care about elements
Indexed for (i, item) in array.enumerated() Need index numbers
Filtered for item in array where condition Only matching elements
Higher-order array.map { } Transform each element
Filter array.filter { } Keep elements that match

(1) Basic and Filtered Traversal

SWIFT
let numbers = [3, 7, 2, 8, 5, 1, 9, 4, 6]
// Basic for-in
for num in numbers {
    print(num, terminator: " ")
}
print()
// where filter
for num in numbers where num > 5 {
    print("\(num) is greater than 5")
}

(2) Higher-Order Functions: map and filter

SWIFT
let prices = [12.99, 24.50, 8.75, 35.00]
// map: add tax to each price
let withTax = prices.map { $0 * 1.08 }
print("With tax: \(withTax)")
// filter: items over 20
let expensive = prices.filter { $0 > 20 }
print("Expensive: \(expensive)")

▶ Example: Order Data Analysis

SWIFT
// ============================================
// Analyzing order data with array operations
// ============================================
let orderAmounts = [45.0, 120.0, 33.5, 299.0, 55.0, 180.0, 22.0]
// 1. Total sales
let total = orderAmounts.reduce(0, +)
print("Total sales: $\(total)")
// 2. High-value orders (>= 100)
let highValue = orderAmounts.filter { $0 >= 100 }
print("High-value orders: \(highValue.count)")
// 3. Add 10% service fee to all orders
let withServiceFee = orderAmounts.map { $0 * 1.1 }
print("First 3 with fee: \(Array(withServiceFee.prefix(3)))")
// 4. Sort
let sorted = orderAmounts.sorted(by: >)
print("Top 3: \(Array(sorted.prefix(3)))")

Output:

TEXT 📖 Display only
Total sales: $754.5
High-value orders: 3
First 3 with fee: [49.5, 132.0, 36.85]
Top 3: [299.0, 180.0, 120.0]

6. Full Example: Shopping Cart Management System

SWIFT
// ============================================
// Shopping cart management system
// Combining array CRUD, traversal, and higher-order functions
// ============================================
import Foundation
var cartItems: [String] = []
var cartPrices: [Double] = []
func addItem(name: String, price: Double) {
    cartItems.append(name)
    cartPrices.append(price)
    print("Added: \(name) - $\(price)")
}
func removeItem(at index: Int) {
    guard index >= 0 && index < cartItems.count else {
        print("Invalid index")
        return
    }
    let removed = cartItems.remove(at: index)
    cartPrices.remove(at: index)
    print("Removed: \(removed)")
}
func updateQuantity(name: String, newPrice: Double) {
    if let index = cartItems.firstIndex(of: name) {
        cartPrices[index] = newPrice
        print("Updated: \(name) -> $\(newPrice)")
    }
}
func checkout() {
    guard !cartItems.isEmpty else {
        print("Cart is empty")
        return
    }
    print("\n=== Shopping Cart ===")
    var total = 0.0
    for (i, item) in cartItems.enumerated() {
        let price = cartPrices[i]
        total += price
        print("\(i + 1). \(item) - $\(String(format: "%.2f", price))")
    }
    let tax = total * 0.08
    let grandTotal = total + tax
    print("---")
    print("Subtotal: $\(String(format: "%.2f", total))")
    print("Tax (8%): $\(String(format: "%.2f", tax))")
    print("Total: $\(String(format: "%.2f", grandTotal))")
    let expensiveItems = cartPrices.enumerated().filter { $0.element > 100 }
    if !expensiveItems.isEmpty {
        print("\nHigh-value items:")
        for (i, _) in expensiveItems {
            print("  - \(cartItems[i])")
        }
    }
}
addItem(name: "Laptop", price: 999.0)
addItem(name: "Mouse", price: 25.0)
addItem(name: "Keyboard", price: 89.0)
addItem(name: "Monitor", price: 349.0)
addItem(name: "USB Hub", price: 35.0)
removeItem(at: 4)
updateQuantity(name: "Mouse", newPrice: 22.5)
checkout()

Output:

TEXT 📖 Display only
Added: Laptop - $999.0
Added: Mouse - $25.0
Added: Keyboard - $89.0
Added: Monitor - $349.0
Added: USB Hub - $35.0
Removed: USB Hub
Updated: Mouse -> $22.5

=== Shopping Cart ===
1. Laptop - $999.00
2. Mouse - $22.50
3. Keyboard - $89.00
4. Monitor - $349.00
---
Subtotal: $1459.50
Tax (8%): $116.76
Total: $1576.26

High-value items:
  - Laptop
  - Monitor

❓ FAQ

Q What happens with an out-of-bounds array access?
A The program crashes (runtime error). Always ensure index < array.count before subscript access, or check with indices.contains(index).
Q What's the performance difference between append and insert?
A append is O(1) (adds to the tail). insert is O(n) (needs to shift subsequent elements). For frequent insertions at the head, consider other data structures (e.g., linked lists).
Q Is Array a value type or a reference type?
A Array is a value type (struct). Assigning to a new variable creates a copy; modifying the copy does not affect the original array.
Q How do I merge two arrays?
A Use the + operator: let combined = array1 + array2. Or use append(contentsOf:) to add all elements from another array.
Q Does removeAll free memory?
A removeAll() clears elements but keeps the capacity. To also release memory, use removeAll(keepingCapacity: false).

📖 Summary


📝 Exercises

  1. Beginner: Create an array of 5 city names. Use for-in to print "I love [city name]" for each one, one line each.
  2. Intermediate: Write a student grade management system: initialize a scores array [78, 92, 55, 88, 73], implement adding new scores, removing failing scores (<60), calculating the average, and finding the highest score.
  3. Challenge: Implement a simple "cart recommendation" feature. Given a cart array ["Laptop", "Mouse", "Keyboard"] and a recommendation rules table (Laptop → Laptop Bag, Mouse → Mouse Pad, Keyboard → Wrist Rest), auto-generate recommended items and add them to the cart. Do not add items already present.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏