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

What is the the difference between assigning an empty value to a variable versus variable with just type annotation?

What is the the difference between assigning an empty value to a variable versus variable with just type annotation in swift 2.

Here is an example of my code: How come the top one works in comparison with the bottom one?

let hourOfDay = 12
let timeOfDay: String

if hourOfDay < 6 {
    timeOfDay = "Early Morning"
} else if hourOfDay < 12 {
    timeOfDay = "Morning"
} else if hourOfDay < 17 {
    timeOfDay = "Afternoon"
} else if hourOfDay < 20 {
    timeOfDay = "Evening"
} else if hourOfDay < 24 {
    timeOfDay = "Late Evening"
} else {
    timeOfDay = "INVALID HOUR!"
}
______________________________
let hourOfDay = 12
let timeOfDay = ""

if hourOfDay < 6 {
    timeOfDay = "Early Morning"
} else if hourOfDay < 12 {
    timeOfDay = "Morning"
} else if hourOfDay < 17 {
    timeOfDay = "Afternoon"
} else if hourOfDay < 20 {
    timeOfDay = "Evening"
} else if hourOfDay < 24 {
    timeOfDay = "Late Evening"
} else {
    timeOfDay = "INVALID HOUR!"
}

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,863 Points

Hey Kevin,

It has to do with using let as opposed to var.

In your first code block, you have declared a constant called timeOfDay to be a string, but it is not initialized. So, as you know, when you use let, the value cannot be changed. But, because you only declared it and didn't initialize it, there is no value, so you aren't changing anything. When your if/else block runs, it is assigning (or initializing) timeOfDay for the first time.

In your second code block, you are declaring and initializing timeOfDay with an empty string. Swift doesn't care if the string is empty or not, it only cares that something (in this case the empty string) was assigned (initialized) to the constant. And, because they cannot be changed, the if/else block cannot assign the new value to it.

I hope that makes sense and helps to clear it up for you. Keep Coding! :dizzy:

Jason,

Thank you for your time and knowledge. I spent the last couple hours trying to figure it out and it usually is the simplest of mistake I often overlook.