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 Swift Basics (retired) Types Numbers and Booleans

Ross Freeman
Ross Freeman
5,522 Points

When implicitly defining a variable like 1.0, does Swift define it as a double or a float?

The video explains how you can differentiate between a double and a float by explicitly defining it in the variable. But if you implicitly define a variable, does the variable become a float or a double?

5 Answers

Ross Freeman
Ross Freeman
5,522 Points

Found the answer in the Apple documentation: "Swift always chooses Double (rather than Float) when inferring the type of floating-point numbers."

Please always forego the use of implicit types in decimals, use explicit type!

In other words, don't let swift decide for you on decimal numbers like so:

var x = 1.0

You should always explicitly declare variables as such in order to prevent errors where you need to know the type of inputs such as function arguments! Also, this is good practice as if you need the precision, use double (such as calculating very large or small numbers accurately) or if you need relative precision but more speed, use float.

Example:

var x = 3.15

func areaOfCircle(radius: Float) - > Float { ... }

areaOfCircle(x) # This will not work as x is a different type (Double, implicit casting) It needs a float!

stevenstabile
stevenstabile
9,763 Points

Thank you. Coming from C++ I was a little surprised (unless it's addressed later) that he didn't mention that you can specify Float in order to save memory unless you need the extra precision.

I HAVE NO IDEA! XD

Ross Freeman
Ross Freeman
5,522 Points

Good to know I'm not alone lol!

but its actually defines as double since the value can be changed.

Ross Freeman
Ross Freeman
5,522 Points

But how would that be different from a float? If you declare it as a var, it can be changed either way.

Vicdaly Williams
PLUS
Vicdaly Williams
Courses Plus Student 187 Points

It automatically declares it as a double because it is more specific ,although you can declare it as a float