Array Operations in Swift

Master essential array manipulation techniques in Swift, including filtering elements, mapping values, and sorting arrays.

Array Operations in Swift
Photo by Maxim Hopman / Unsplash

Master essential array manipulation techniques in Swift, including filtering elements, mapping values, and sorting arrays.

// Filter elements in an array
let numbers = [1, 2, 3, 4, 5, 6]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print(evenNumbers) // [2, 4, 6]

// Map elements in an array
let doubledNumbers = numbers.map { $0 * 2 }
print(doubledNumbers) // [2, 4, 6, 8, 10, 12]

// Sort an array of strings
var fruits = ["Apple", "Banana", "Orange"]
fruits.sort { $0 < $1 }
print(fruits) // ["Apple", "Banana", "Orange"]