Reputation: 313
I want to create a list of integers on an interval increasing with a certain step, for example [0,1,2,3,4,5,6,7,8,9,10]. How could I do this without creating a separate method?
Upvotes: 2
Views: 356
Reputation: 70111
Swift 2
To create an array of Ints in sequence you can use a "range":
let a = Array(0...10) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Here 0...10
makes the Range and the Array initializer makes the Range into an Array of Ints.
There's also this variant:
let a = Array(0..<10) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
And to do the same thing but with a different stepping, you can use "stride":
let b = Array(0.stride(through: 10, by: 2)) // [0, 2, 4, 6, 8, 10]
Here stride
starts on 0 and goes through 10 by steps of 2.
It also has a variant:
let b = Array(0.stride(to: 10, by: 2)) // [0, 2, 4, 6, 8]
Swift 3
The syntax for stride
has changed, now it's a free function.
let b = Array(stride(from: 0, through: 10, by: 2)) // [0, 2, 4, 6, 8, 10]
let b = Array(stride(from: 0, to: 10, by: 2)) // [0, 2, 4, 6, 8]
Upvotes: 4