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 trialJason Hernandez Berland
1,575 PointsDo you have to declare implicit type?
On Amit's example, he writes var str : String = "Hello "
Is :String
necessary and/ or best practices?
2 Answers
Ben Griffith
5,808 PointsIn this instance it's not necessary to declare that it's a String as Swift will infer the correct type because you're initialising the variable str with a string literal ("Hello").
You can use literals to get Swift to infer the type without having to declare it.
So we can do the following;
// Use string literals to get Swift to infer as String
var str = "hello"
// Use boolean literals to get Swift to infer as Boolean
var goodWeather = false
// Use floating-point literals to get Swift to infer as Double
var pi = 3.14159265359
// etc
A quick thing to note on using floating-point literals;
Swift always chooses Double (rather than Float) when inferring the type of floating-point numbers.
So if you specifically need a float you'll have to declare the type.
If you're not setting any values with literals, then you will need to define the type. Otherwise you'll get the following error;
"Type annotation missing in pattern"
As for best practices, Apple tend not to explicitly declare types when literals are used. A good read is the Swift language guide from Apple.
You should specifically check out the Type Safety and Type Inference section within The Basics chapter
Hope this helps a bit more.
Jason Hernandez Berland
1,575 PointsChecked out the link but can't find answer
Jason Hernandez Berland
1,575 PointsJason Hernandez Berland
1,575 PointsGood lookin' out @Ben Griffith !