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 trialRoss Freeman
5,522 PointsWhen 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
5,522 PointsFound the answer in the Apple documentation: "Swift always chooses Double (rather than Float) when inferring the type of floating-point numbers."
tech1337
2,520 PointsPlease 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
9,763 PointsThank 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.
Chai Jags
480 PointsI HAVE NO IDEA! XD
Ross Freeman
5,522 PointsGood to know I'm not alone lol!
Chai Jags
480 Pointsbut its actually defines as double since the value can be changed.
Ross Freeman
5,522 PointsBut how would that be different from a float? If you declare it as a var, it can be changed either way.
Vicdaly Williams
Courses Plus Student 187 PointsIt automatically declares it as a double because it is more specific ,although you can declare it as a float