Simplifying Array Initialization in Swift with Array(repeating:)

When developing in Swift, a common requirement is to initialize an array where multiple elements share the same initial value. This scenario can arise in various contexts, such as setting up default configurations, pre-filling data structures, or initializing state for UI components. Manually listing each element is not only tedious but can also lead to longer code and increased risk of errors.

Swift provides a highly efficient and concise method for handling such cases: the Array(repeating:count:) initializer. This tool allows developers to create arrays with multiple copies of the same element, ensuring code is clean and maintainable.

enum HorizontalIndent {
  case left
  case right

  func toggle() -> HorizontalIndent {
    self == .left ? .right : .left
  }
}
let startHorizontalIndent: HorizontalIndent = .left
let horizontalIndents: [HorizontalIndent] = [
      startHorizontalIndent,
      startHorizontalIndent,
      startHorizontalIndent,
      startHorizontalIndent,
      startHorizontalIndent.toggle(),
      startHorizontalIndent.toggle(),
      startHorizontalIndent.toggle(),
      startHorizontalIndent.toggle()
    ]

//Here's how you could refactor your code:

// Create the array using an initializer and map to generate toggled values
let horizontalIndents: [HorizontalIndent] = Array(repeating: startHorizontalIndent, count: 4) +
                                             Array(repeating: startHorizontalIndent.toggle(), count: 4)