WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Day 4- why cant declare range 1...10 as Int type?

Forums > 100 Days of Swift

Hi, below are 2 examples, first has error after declaring constant range as Int type. When declaring range to constant, how is it stored? As an array of strings or integers?

//ERROR:

let number : Int = 1...10 //error: Cannot convert value of type 'ClosedRange<Int>' to specified type 'Int'

for count in number{ //error: For-in loop requires 'Int' to conform to 'Sequence' print(count) }

print(number)

//WORKS BELOW after removing ":Int" declaration.

let number = 1...10

for count in number{ print(count) }

print(number) //but doesn't print as array. prints "1...10\n" like a string, so im confused. is it integer or string?

1      

When declaring range to constant, how is it stored?

As a range type. In this case, it's a ClosedRange<Int> as the error message tells you.

//WORKS BELOW after removing ":Int" declaration.

let number = 1...10

Because by removing the :Int type annotation, the compiler can infer the type directly from the value 1...10.

print(number) //but doesn't print as array. prints "1...10\n" like a string, so im confused. is it integer or string?

It's neither an array nor an integer nor a string, it's a range. If you want to get a range as an array of integers, you need to convert it, like so:

let rng = 1...10
let array = Array(rng)
print(rng)
//prints 1...10
print(array)
//prints [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2      

Wow, thanks man! I did not realise range is also a data type.

btw, is there a notification to inform me when my question has been replied in the forum?

1      

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.