2

I am not able to print array values in swift. My code is:

var array = 1...10
println(array)

The result is:

VSs5Range (has 2 children)

But when I try to print the following array, it works:

var array = [1,2,3,4,5,6,7,8,9,10]
println(array)

Result is:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Why isn't the first one printing correctly?

2 Answers 2

6

The expression 1...10 returns a Range, not an Array. Internally, a Range stores two values (a start and an end); an Array, on he other hand, is a dynamic structure containing "n" values.

Sign up to request clarification or add additional context in comments.

6 Comments

so how to print array values ?
@Manimurugan You did it well in your second example.
Le I want to print my First array ? cant i print ?
@JeanLeMoignan Just wanted to highlight that you used 1..10 where his example shows 1...10
Your first variable is not an array. Is Range!
|
2

As explained,

var array = 1...10

array, in this case, is a Range object, not an array If you want to print its content do this (changed the name to something more suitable)

    var range = 1...10

    for value in range
    {
        println(value)
    }

2 Comments

how can i print current index inside the for loop ?
as explained, a range has only two values, a start and an end. It doesn't have any index. If you want to "simulate" simply add var idx = 0 before the for, and idx++ inside the for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.