Back to Blog

Swift: Add 1 to each element in the array

Sandy LaneSandy Lane

Video: Swift: Add 1 to each element in the array by Taught by Celeste AI - AI Coding Coach

Watch full page →

Swift: Add 1 to Each Element in the Array Using Closure

In Swift, you can easily add 1 to every element in an array by using the map function combined with a closure. This approach applies a transformation to each element, returning a new array with the incremented values without modifying the original array.

Code

let numbers = [1, 2, 3, 4, 5]

// Use map with a closure to add 1 to each element
let incrementedNumbers = numbers.map { number in
  number + 1
}

print(incrementedNumbers)  // Output: [2, 3, 4, 5, 6]

Key Points

  • The map function transforms each element of an array using a closure.
  • Closures can be written with explicit parameters or shorthand syntax like { $0 + 1 }.
  • Using map returns a new array without modifying the original.
  • This technique is concise and expressive for element-wise operations on arrays.