SWIFT – Create filled array using map

A useful trick using .map:

Random Int value array:

array[0] = 1
array[1] = 5
array[2] = 3
[…]
array[30] = 1

The function, using map become:

func generateArray() -> [Int] {
  let monthDays = Calendar.current.numberOfDaysInMonthForDate(Date())

   let array = (0..<monthdays).map { _ -> Int in
     return Int(Double(arc4random_uniform(5)))
  }

  return array
}

Array of IndexPaths:

let allIndexes: [IndexPath] = (0..<10).map {
    return IndexPath(row: $0, section: 0)
}

And so on…

Enjoy mapping!

 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.