You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Swift provides three primary collection types: Array, Set, and Dictionary. All three are generic, type-safe, and implemented as value types with copy-on-write optimisation.
An array is an ordered collection of elements of the same type:
// Creating arrays
var fruits: [String] = ["Apple", "Banana", "Cherry"]
var numbers = [1, 2, 3, 4, 5] // inferred as [Int]
var empty: [Double] = []
var repeated = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0]
// Accessing
let first = fruits[0] // "Apple"
let last = fruits.last // Optional("Cherry")
let count = fruits.count // 3
let isEmpty = fruits.isEmpty // false
// Modifying
fruits.append("Date") // ["Apple", "Banana", "Cherry", "Date"]
fruits.insert("Elderberry", at: 1)
fruits.remove(at: 0)
fruits[0] = "Blueberry"
// Safe access with bounds checking
if let item = fruits.first {
print("First fruit: \(item)")
}
for fruit in fruits {
print(fruit)
}
for (index, fruit) in fruits.enumerated() {
print("\(index): \(fruit)")
}
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.