Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to instantly generate an array filled with a range of values in Swift?

For example, in python I could say something along the lines of

arr = range(0,30) 

and get an array with said elements. I suspect that something similar might be possible with a subscript in Swift, but after scouring the documentation and Apple's iBook I can't find a "batteries-included" solution for generating said array.

Is this something I'd have to write the code manually for, or is there a pre-written method for it?

like image 779
hansvimmer Avatar asked Dec 29 '14 07:12

hansvimmer


4 Answers

You can create an array with a range like this:

var values = Array(0...100) 

This give you an array of [0, ..., 100]

like image 93
Kalenda Avatar answered Sep 24 '22 12:09

Kalenda


You can create a range and map it into an array:

var array = (0...30).map { $0 } 

The map closure simply returns the range element, resulting in an array whose elements are all integers included in the range. Of course it's possible to generate different element and types, such as:

var array = (0...30).map { "Index\($0)" } 

which generates an array of strings Index0, Index1, etc.

like image 23
Antonio Avatar answered Sep 21 '22 12:09

Antonio


You can use this to create array that contains same value

let array = Array(count: 5, repeatedValue: 10)

Or if you want to create an array from range you can do it like this

let array = [Int](1...10)

In this case you will get an array that contains Int values from 1 to 10

like image 25
mustafa Avatar answered Sep 22 '22 12:09

mustafa


create an Int array from 0 to N-1

var arr = [Int](0..<N)

create a Float array from 0 to N-1

var arr = (0..<N).map{ Float($0) }

create a float array from 0 to 2π including 2π step 0.1

var arr:[Float] = stride(from: 0.0, to: .pi * 2 + 0.1, by: 0.1).map{$0}
or
var arr:[Float] = Array(stride(from: 0.0, to: .pi * 2 + 0.1, by: 0.1))
like image 26
lbsweek Avatar answered Sep 20 '22 12:09

lbsweek