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 trial

iOS

Tobi Tron
Tobi Tron
2,737 Points

Why Int in simple app w/ Swift random number variable?

In the finishing up our model stage of simple iPhone app w/ Swift Pasan creates this random number variable:

var random number = Int(arc4_random_uniform(10))

I don't understand why Int is in there. I thought that Swift implicitly figures out data types. 10 is clearly not a Float/Double so why is Int necessary?

2 Answers

Pasan Premaratne
STAFF
Pasan Premaratne
Treehouse Teacher

Tobias Kahn

arc4_random_uniform() returns an unsigned 32 bit integer. Integer types that are unsigned can only represent non-negative numbers. Since we can access an array with negative integers as well (for example: -1 gets the last item in an array), array subscripting accepts an signed integer of type Int so we need to cast it to the right type.

It's not that Swift is inferring the wrong type here. Swift knows it's of type UInt32 and will spit out a compiler error so we cast it to Int to make it work.

Hope that helps!

I'll go out on a limb and say that arc4_random_uniform() probably returns a float. By passing its return value to Int, Pasan is basically telling the compiler that he wants an int back, not a float. It's called casting, short for typecasting.