SWIFT – Create filled array using map

A simple trick using .map to create directly a new Int array with random numbers inside.

The function produce this output:

array[0] = 1
array[1] = 5
array[2] = 3
[...]
array[30] = 1
func generateArray() -> [Int] {
let monthDays = Calendar.current.numberOfDaysInMonthForDate(Date())

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

return array
}

That’s all!

Comments are closed, but trackbacks and pingbacks are open.

Follow on Feedly