How to create an array with incremented values in Swift?

Swift

Swift Problem Overview


I know that I can create an array with repeated values in Swift with:

var myArray = [Int](count: 5, repeatedValue: 0)

But is there a way to create an array with incremented values such as [0, 1, 2, 3, 4] other than to do a loop such as

var myArray = [Int]()
for i in 0 ... 4 {
    myArray.append(i)
}

I know that code is pretty straightforward, readable, and bulletproof, but it feels like I should be able pass some function in some way to the array as it's created to provided the incremented values. It might not be worth the cost in readability or computationally more efficient, but I'm curious nonetheless.

Swift Solutions


Solution 1 - Swift

Use the ... notation / operator:

let arr1 = 0...4

That gets you a Range, which you can easily turn into a "regular" Array:

let arr2 = Array(0...4)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDribblerView Question on Stackoverflow
Solution 1 - Swiftluk2302View Answer on Stackoverflow