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) Variables and Constants Constants

explicit variable type?

Why would someone want to specify the type of a variable?

for example : var greeting: String = "Hello"

Why add "String" to it? is it just for better readability?

1 Answer

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

Hi Jesus Lopez If you declare a variable without assigning a value it, then you have to specify the type

var greeting: String

But in the case of var greeting: String = "Hello", you don't have to do that, Swift can determine the variable's type by the value it's being assigned to. I'd argue that specifying a type here doesn't bring anything to the table when it comes to readability, because by reading the code, one can easily tell what the variable's type is by its assigned value, so it's best to write it as var greeting = "Hello" for the sake of simplicity.

I think the reason that Amit Bijlani shows you how to specify type for variable during the lecture isn't because that he's suggesting that you should always write the variable assignment this way; he's simply just teaching students this concept and allow you to familiarize with it a bit, so that you won't get too confused as you progress through lectures and eventually come across topics like specifying types for Struct, function argument and return value.