← Back to Swift Course | Chapter 6: Collections | Lesson 1 of 7

Arrays

An array is an ordered list of things, like a row of lockers each holding one item, numbered starting from zero.

Creating and Accessing Arrays

An array is created with square brackets containing comma-separated values, and its elements are accessed by zero-based integer index.

Example: Creating and Accessing Arrays

markup
var fruits = ["apple", "banana", "cherry"]
print(fruits[0])
print(fruits[2])
print("Total fruits: \(fruits.count)")

Modifying an Array

Elements can be added with .append(), removed with .remove(at:), and updated by assigning directly to an index.

Example: Modifying an Array

markup
var numbers = [1, 2, 3]
numbers.append(4)
numbers.remove(at: 0)
numbers[0] = 99
print(numbers)

Checking Array Contents

Properties like .isEmpty and .count, along with methods like .contains(), help inspect an array without manual loops.

Example: Checking Array Contents

markup
let scores = [80, 95, 70]
print("Is empty: \(scores.isEmpty)")
print("Count: \(scores.count)")
print("Contains 95: \(scores.contains(95))")
Common Mistakes
  1. Trying to access an index that's out of bounds, e.g. array[10] on a 3-element array, which crashes at runtime instead of returning nil.
  2. Forgetting that arrays declared with let are immutable -- you cannot append or remove elements from a constant array.
  3. Confusing .count (number of elements) with the last valid index, which is .count - 1.
Chapter Summary
  • An array is an ordered, indexable collection of values of the same type, written as [Type].
  • Arrays declared with var can be modified; those declared with let cannot.
  • Common operations include .append(), .remove(at:), .count, and indexing with [].
  • Accessing an out-of-bounds index crashes the program at runtime.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.