Arrays
Understanding Arrays in Swift
What is it?
An Array is an ordered collection of values of the same type. You can store multiple items in a single variable and access them by their position (index). Arrays are written as [value1, value2, value3].
Why does it exist?
Arrays are essential when you need to work with multiple related items - like a list of names, a collection of numbers, or a series of user inputs. Instead of creating separate variables for each item (name1, name2, name3...), you can manage them all together in one array.
Examples
Basic
Example 1
let fruits = ["Apple", "Banana", "Orange"]Creating an array of strings
Intermediate
Example 1
var numbers = [1, 2, 3]
numbers.append(4)
let first = numbers[0] // 1
let count = numbers.count // 4Adding items and accessing elements by index
Advanced
Example 1
let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map { $0 * 2 } // [2, 4, 6, 8, 10]
let evens = numbers.filter { $0 % 2 == 0 } // [2, 4]Using array methods for transformation
Common Mistakes
Common mistakes with arrays: 1. Wrong index: let items = ["a", "b"]; items[2] (Error! Index out of range) 2. Mixing types: let mixed = [1, "two", 3.0] (Error in typed languages!) 3. Forgetting arrays start at 0: First item is [0], not [1] 4. Modifying immutable arrays: let items = [1, 2]; items.append(3) (Error! Use 'var' instead)
Write it once before proceeding
This helps your brain start forming the pattern.
let numbers = [1, 2, 3, 4, 5]Arrays are like toy boxes
Simple Explanation
An array is like a toy box that holds things in order. You can put toys in, take toys out, and find a toy by counting which spot it's in. The first toy is in spot 0, the second is in spot 1, and so on.
Think of it like this
Imagine you have a row of numbered cubbies at school. Each cubby holds one thing, and you can find your stuff by remembering which number it's in. That's exactly how arrays work!
Tiny Example
let colors = ["Red", "Blue", "Green"] // A list of three colors in orderCore Drill: Lock It In
Write the same concept 50 times to make it permanent. Your progress is saved automatically.
Sign In to Unlock
Complete all 50 repetitions and lock this concept in your memory forever.
Ready to Lock This In?
Sign in with Google to start your 50 repetitions and make this concept stick forever.
