Arrays are fundamental data structures in Swift programming. They store ordered collections of values of the same type, allowing efficient access and manipulation of data.
In Swift, you can create arrays using various syntaxes:
// Empty array of integers
let emptyArray: [Int] = []
// Array with initial values
let fruits = ["Apple", "Banana", "Orange"]
// Array with repeated values
let fiveZeros = Array(repeating: 0, count: 5)
Swift provides several methods to interact with arrays:
fruits[0]
fruits.append("Mango")
fruits.remove(at: 1)
fruits[2] = "Grape"
Swift arrays support various operations for efficient data manipulation:
let numbers = [1, 2, 3, 4, 5]
// Filtering
let evenNumbers = numbers.filter { $0 % 2 == 0 }
// Mapping
let doubledNumbers = numbers.map { $0 * 2 }
// Reducing
let sum = numbers.reduce(0, +)
Swift supports nested arrays, allowing you to create multidimensional data structures:
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
let element = matrix[1][2] // Accesses 6
You can extract portions of an array using slicing:
let numbers = [1, 2, 3, 4, 5]
let slice = numbers[1...3] // [2, 3, 4]
let
for immutable arrays and var
for mutable onesArrays in Swift are versatile and powerful. They integrate seamlessly with other Swift features like Closures and Optionals, making them essential for effective Swift programming.