Arrays
Reviewed & published by Brayan K
Arrays are ordered lists — the workhorse collection of everyday code. By the end of this lesson you'll declare arrays of type [T], add and remove elements, access by index safely, and loop over every value.
Part of the free Swift course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
- • Declare arrays with the [T] type syntax
- • Add and remove elements with append, insert, remove(at:)
- • Access elements by zero-based index — and avoid out-of-range crashes
- • Use count, isEmpty, first, last
- • Iterate with for-in and enumerated()
1️⃣ Declaring Arrays
An array holds an ordered list of values of one type, written [Element]. Swift can infer the type from a literal, or you can annotate it — handy when starting empty.
// An ARRAY is an ordered list of values, ALL of the same type.
// The type is written as [Element], e.g. [String] or [Int].
let fruits = ["apple", "banana", "cherry"] // inferred as [String]
print(fruits) // ["apple", "banana", "cherry"]
// Explicit type annotation — and an empty array to fill later.
var scores: [Int] = []
print(scores.isEmpty) // true
// You can also write the empty form with the type's initializer.
var flags = [Bool]()
print(flags.count) // 02️⃣ Adding & Removing Elements
To change an array it must be a var. Use append to add to the end, insert(_:at:) at a position, and remove(at:) to delete.
// To CHANGE an array it must be a var.
var todo = ["wash", "cook"]
todo.append("clean") // add to the end
print(todo) // ["wash", "cook", "clean"]
todo.insert("plan", at: 0) // add at a position (everything shifts right)
print(todo) // ["plan", "wash", "cook", "clean"]
todo.remove(at: 1) // remove by index
print(todo) // ["plan", "cook", "clean"]
todo[0] = "schedule" // replace by index
print(todo) // ["schedule", "cook", "clean"]
// Note: a 'let' array is fixed — you cannot append to it.3️⃣ Accessing Elements Safely
Arrays are zero-indexed: the first element is arr[0]. Reading an out-of-range index crashes, so prefer first/last (optionals) or check count when you're not sure.
// Arrays are ZERO-INDEXED: the first element is at index 0.
let colours = ["red", "green", "blue"]
print(colours[0]) // red
print(colours[2]) // blue
// Handy, crash-proof accessors:
print(colours.first ?? "none") // red (first is an optional)
print(colours.last ?? "none") // blue (last is an optional)
print(colours.count) // 3
print(colours.isEmpty) // false
// ⚠️ colours[10] would CRASH: "Index out of range".
// Check the count first, or use indices, to stay safe.4️⃣ Iterating Over an Array
A for-in loop visits each element in order. When you also need the index, enumerated() hands you (index, element) pairs.
// Loop over every element with for-in.
let nums = [10, 20, 30]
for n in nums {
print("value: \(n)")
}
// Need the position too? enumerated() gives (index, element) pairs.
let names = ["Ann", "Ben", "Cara"]
for (i, name) in names.enumerated() {
print("\(i): \(name)")
}
// Arrays compose nicely with other tools, e.g. a running total.
var total = 0
for n in nums { total += n }
print("total = \(total)") // total = 60Your turn. Fill in the blanks, then run it and check the output.
// 🎯 YOUR TURN — replace each ___ then run it in SwiftFiddle.
// 1) Make a MUTABLE array of Int called 'days' with 1, 2, 3.
var days: [Int] = ___ // 👉 e.g. [1, 2, 3]
// 2) Append the number 4 to the end.
days.___(4) // 👉 replace ___ with append
// 3) Print how many numbers are now in the array.
print("count = \(days.___)") // 👉 replace ___ with count
// 4) Loop and print each number.
for d in days {
print(d)
}
// ✅ Expected output:
// count = 4
// 1
// 2
// 3
// 4Pro Tips
- 💡 Default to let. Only use var when the list genuinely changes.
- 💡 Use first/last instead of arr[0] when the array might be empty — they return optionals, not crashes.
- 💡 Loop the elements, not the indexes. for item in arr is clearer and safer than indexing in a counter loop.
- 💡 Combine arrays with +, e.g. a + b, to make a new joined array.
Common Errors (and the fix)
- "Fatal error: Index out of range" — you read past the end. Check index < arr.count or use first/last.
- "Cannot use mutating member on immutable value" — you called append on a let array. Declare it as var.
- "Cannot convert value of type 'String' to expected element type 'Int'" — arrays are homogeneous. Keep all elements the same type.
- Empty literal needs a type — var a = [] is ambiguous. Write var a: [Int] = [].
📋 Quick Reference
| Task | Code | Result |
|---|---|---|
| Declare | let a = [1, 2, 3] | [Int] |
| Empty | var a: [Int] = [] | mutable, empty |
| Append | a.append(4) | adds to end |
| Index | a[0] | first element |
| Count | a.count | number of items |
| Loop | for x in a { … } | visits each |
Mini-Challenge: Shopping List
Build it, run it, and check your output against the example in the comments.
// 🎯 MINI-CHALLENGE: Shopping list
// 1. Make a var array 'cart' of String, starting empty: var cart: [String] = []
// 2. Append three items (e.g. "milk", "eggs", "bread").
// 3. Print "You have N items:" using cart.count for N.
// 4. Loop with enumerated() to print each as "1. milk", "2. eggs", ...
// (remember indexes start at 0, so print i + 1).
//
// ✅ Example output:
// You have 3 items:
// 1. milk
// 2. eggs
// 3. bread
// your code here🎉 Lesson Complete!
- ✅ Array types are written [T]; elements share one type
- ✅ Mutate var arrays with append, insert, remove(at:)
- ✅ Arrays are zero-indexed; out-of-range access crashes — use first/last
- ✅ Inspect with count and isEmpty; loop with for-in
Practice quiz
How do you write the type of an array of Strings?
- Array(String)
- [String]
- String[]
- <String>
Answer: [String]. Swift array types are written as [Element], e.g. [String].
What does the first element of an array have as its index?
- 1
- 0
- -1
- It has no index
Answer: 0. Swift arrays are zero-indexed, so the first element is at index 0.
Which method adds an element to the end of a var array?
- arr.add(x)
- arr.push(x)
- arr.append(x)
- arr.insertLast(x)
Answer: arr.append(x). append(_:) adds an element to the end of the array.
How do you get the number of elements in an array?
- arr.length
- arr.size()
- arr.count
- arr.len
Answer: arr.count. The count property returns the number of elements.
What happens if you read arr[10] on an array with 3 elements?
- Returns nil
- Returns 0
- Runtime crash (index out of range)
- Returns the last element
Answer: Runtime crash (index out of range). Accessing an out-of-bounds index crashes at runtime.
Can you append to an array declared with `let`?
- Yes, always
- No — let arrays are immutable
- Only if it's empty
- Only the first time
Answer: No — let arrays are immutable. A let array is constant; use var to be able to append or modify it.
What does [1, 2, 3].isEmpty return?
- true
- false
- 3
- nil
Answer: false. isEmpty is false because the array has elements.
How do you create an empty array of Int that you can append to?
- var nums: [Int] = []
- let nums = []
- var nums = Int[]
- var nums: Int = 0
Answer: var nums: [Int] = []. var nums: [Int] = [] makes a mutable empty Int array.
Which loop visits every element of an array `items`?
- for item in items { ... }
- loop items { ... }
- each items { ... }
- items.for { ... }
Answer: for item in items { ... }. A for-in loop iterates over each element directly.
Are all elements of a Swift array required to be the same type?
- No, mix freely
- Yes — an array is homogeneous
- Only for numbers
- Only when using let
Answer: Yes — an array is homogeneous. A Swift array holds elements of one type, e.g. [Int] holds only Ints.
Continue this course
- Previous: Strings & String Interpolation
- Next: Dictionaries & Sets — Key-value lookups with dictionaries and unique collections with sets
Frequently asked questions
How do I write the type of an array in Swift?
Use square brackets around the element type: [Int] is an array of integers, [String] an array of strings. This is shorthand for Array<Element>. Because an array is homogeneous, every element must be that one type — you cannot freely mix Ints and Strings in the same array.
What is the difference between a let array and a var array?
A let array is a constant: its contents are fixed and you cannot append, remove, or replace elements. A var array is mutable, so you can call append, insert, remove(at:), and assign new values by index. Reach for let by default and switch to var only when the list really needs to change.
Why does accessing an out-of-range index crash instead of returning nil?
Subscripting with an integer index (arr[i]) is defined to return a non-optional element, so Swift can't return nil — an out-of-range access is a programming error and traps at runtime. To avoid it, check i < arr.count first, or use safe accessors like first and last, which are optionals.
How do I loop over an array and get the index too?
A plain for item in array loop gives you each element. When you also need the position, call array.enumerated(), which yields (offset, element) pairs: for (i, item) in array.enumerated(). The offset starts at 0, matching the array's own indexing.
How do I create an empty array I can add to later?
Declare it as a var with an explicit type and an empty literal: var nums: [Int] = []. You can also use the initializer form var nums = [Int](). Either way you get a mutable, empty array ready for append(_:).