Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialConnor Chappell
498 PointsRandom number with switch statements
In the video, after the random number is generated, the playground has the number as 78 on the right hand side. But when the switch statements are implemented, the 0-32 range is printed out.
Shouldn't the 70-100 range be printed instead?
2 Answers
jcorum
71,830 PointsConnor, if you put this code in a Playground and run it a few times you will see that each time it runs you get a different random number, as well as one of the 5 letters:
var randomTemperature = Int(arc4random_uniform(UInt32(150)))
switch randomTemperature {
case 0..<32: print("A")
case 32..<45: print ("B")
case 45..<70: print("C")
case 70..<100: print("D")
default: print("E")
}
randomTemperature will be a number between 0 and 149, and depending on what number it is, the appropriate case statement will print a letter.
Note: I changed Pasan's code slightly, so that each case was mutually exclusive, and E would be printed for numbers between 100 and 149.
Connor Chappell
498 PointsI was also able to run the original code in the Playground, and was able to get a variety of random numbers, as well as the correct print statements to those numbers. I was just curious why Pasan's code seems to not behave as intended.
jcorum
71,830 PointsSorry, but I don't see how it doesn't "behave as intended"? It generates a random number, and then prints the phrase in the range that contains that number.
The only slight problem that I see is that he has case 32...45 when I think he meant 32..<54.