UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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?

3      

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]

4      

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?

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.