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

Why do you have to use the implicit type?

Why do you have to do the implicit type thing where you specify it is a string? Won't it work as just var str rather than var str : string?

Greg Kitchin
Greg Kitchin
31,522 Points

(Apologies if this is long-winded, I'm needing sleep) There's lots of different types of variables. I've never used Swift, but numbers are a variable type, as are Boolean values (true or false)., and it's common to lots of different languages.

In your example above, var string is a declaration of a variable, with a name, str. So for example, var str = "My Name" makes a variable, called str, with a value of "My Name". Generally, when you're making variables, you give them more specific names. Just to contrast, var myName = "Greg", makes a variable, called myName, with the value "Greg".

I'd say if you want to make sure that strings are treated as strings, and numbers are treated as numbers, explicit typing is the way to go. Having an idea of exactly how a variable should act, would help catch bugs. Because a string can include numbers and characters as well as letters, there's always the chance of errors creeping up. Say for example, I have a line of code, c = a + b

Lets say a and b should be numbers. But I'm tired when I'm writing the code, and I've put "" around them. So if I earlier said that a = "3", and b = "6", I've made them strings. So c = a + b, = "3 " + "6", = "36", instead of 9.

2 Answers

I think you are asking "Why do we have to use explicit type?", since we are using implicit for most of the time. Anyways, for the explicit type, most of the time you don't have to. But sometimes, when you are declaring a variable but you are not assigning any value to it, you may want to specify its type so that the compiler will be able warn you if you try to assign some other type to the variable later in your code.