Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array with incremented values in Swift? [duplicate]

Tags:

swift

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.

like image 639
Dribbler Avatar asked Jan 02 '16 21:01

Dribbler


People also ask

How do I initialize an array in Swift?

To initialize a set with predefined list of unique elements, Swift allows to use the array literal for sets. The initial elements are comma separated and enclosed in square brackets: [element1, element2, ..., elementN] .

What is dynamic array in Swift?

Unlike Objective-C 's NSArray , which can change the value of an element, static arrays are completely static. Like any constant, static arrays use memory far more efficiently than dynamic. Dynamic arrays allow us to change the size and contents of the array, similar to NSMutableArray in Objective-C.


1 Answers

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) 
like image 194
luk2302 Avatar answered Oct 20 '22 16:10

luk2302