Swift — Arrays
Creating arrays
let nums = [1, 2, 3, 4, 5]
var mutable = [String]()
mutable.append("Hello")
mutable.append("World")
// Initialize with count and value
let zeros = Array(repeating: 0, count: 5)
Array operations
var nums = [1, 2, 3, 4, 5]
nums.append(6) // Add to end
nums.insert(0, at: 0) // Insert at index
nums.remove(at: 0) // Remove at index
nums.removeFirst() // Remove first
nums.removeLast() // Remove last
print(nums) // [2, 3, 4, 5, 6]
Array methods
let nums = [1, 2, 3, 4, 5]
print(nums.count) // 5
print(nums.isEmpty) // false
print(nums.contains(3)) // true
print(nums.first ?? 0) // 1
print(nums.last ?? 0) // 5
print(nums.sorted()) // [1, 2, 3, 4, 5]
print(nums.reversed()) // [5, 4, 3, 2, 1]
Map, filter, reduce
let nums = [1, 2, 3, 4, 5]
let doubled = nums.map { $0 * 2 }
print(doubled) // [2, 4, 6, 8, 10]
let evens = nums.filter { $0 % 2 == 0 }
print(evens) // [2, 4]
let sum = nums.reduce(0, +)
print(sum) // 15
Chaining
let result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
.filter { $0 % 2 == 0 }
.map { $0 * $0 }
.prefix(3)
.reduce(0, +)
print(result) // 20
Sets
let set: Set = [1, 2, 3, 2, 1]
print(set) // {1, 2, 3}
let a: Set = [1, 2, 3]
let b: Set = [3, 4, 5]
print(a.union(b)) // {1, 2, 3, 4, 5}
print(a.intersection(b)) // {3}
print(a.subtracting(b)) // {1, 2}
Dictionaries
var ages = ["Alice": 30, "Bob": 25]
ages["Charlie"] = 35
ages.removeValue(forKey: "Bob")
print(ages["Alice"] ?? 0) // 30
for (name, age) in ages {
print("\(name): \(age)")
}
Mini Practice
Write Swift code that:
- Creates and manipulates an array
- Chains
filter,map, andreduce - Uses set operations
- Iterates a dictionary with
for
Up Next
In the next lesson, you'll learn about Sets — unordered collections.
Related Topics
Frequently Asked Questions about Arrays
What is Arrays in Swift?
Arrays is a fundamental concept in Swift. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Arrays?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Arrays.
Why is Arrays important in Swift?
Arrays is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.