Swift by Example: Arrays
Working with Swift arrays through this sample code demonstrating array creation with type annotations, accessing elements by index, appending and modifying values, iterating with for-in loops, and functional methods like map and filter.
Code
// Creating arrays
var shoppingList: [String] = ["Eggs", "Milk"]
var numbers = [1, 2, 3, 4, 5]
// Accessing and modifying
print("First item: (shoppingList[0])")
shoppingList.append("Flour")
shoppingList[0] = "Six Eggs"
// Iterating
for item in shoppingList {
print(item)
}
// Iterating with index
for (index, value) in shoppingList.enumerated() {
print("Item (index + 1): (value)")
}
// Functional methods
let doubled = numbers.map { $0 * 2 }
let evens = numbers.filter { $0 % 2 == 0 }Explanation
Arrays in Swift are ordered collections of values. They are type-safe, meaning an array can only contain values of a specific type. You can create an array using the shorthand syntax [Type] or let Swift infer the type from the initial values.
Arrays are zero-indexed. You can access and modify elements using subscript syntax array[index]. Adding elements is done via append() or the += operator. Be careful not to access an index out of bounds, as this will crash the program.
Swift arrays come with powerful functional methods like map, filter, and reduce. These allow you to transform and query arrays concisely without writing explicit loops. Iterating over an array is typically done with a for-in loop.
Code Breakdown
[String] denotes an array of strings with explicit type annotation.shoppingList.append("Flour") adds a new element to the end of the array.enumerated() returns a sequence of (index, value) pairs for iteration.numbers.map { $0 * 2 } transforms each element using a closure.
