Joe Joe - 3 months ago 14
Swift Question

How to set array starting and end indices in swift?

I tried to create an array from 1-100 elements create in playground, but while i'm trying to print it doesn't print the values in the array.

code:

var ab:Array = [1...100]

for i in ab {
print(i)
}


output:
enter image description here

But in the playground it didn't shown any error.
Did i do anything wrong?
Thanks

Answer

You create an array of Range<Int> elements (a single one, 1..<101)

var ab: Array = [1...100] // element TYPE inferred from 1...100
                          // to be Range<Int>
print(ab.dynamicType)
   // Array<Range<Int>>

But I assume you're attempting to create an array of 100 Int elements.

var ab = Array(1...100) // Array with elements intialized to Int,
                        // using Range<Int> to intialize

for i in ab {
    print(i)
} // 1 2 3 ... 100

If you're only looking to print the numbers in the range 1...100, you needn't necessarily create an array if integers to do so (or an array at all). Instead, you could use a single Range<Int> variable and loop over the elements contained in this range. E.g.

let myRange = 1...5 // inferred as type Range<Int>

for i in myRange {
    print(i) // the type of 'i' is Int, the same as in
             // the array case above.
} // 1 2 3 4 5