0

I thought I knew how to declare variables until I just saw this example.

In the example a constant is declared.

let timeOfDay: String

I thought you could not declare a variable/constant without initializing it unless you declared it as an Optional?

Of course the program bombs when I go to print the constant. How is it the compiler allowed this? I entered this into a Playground.

A full example:

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!"
}
print(timeOfDay)
3
  • Let's see the rest of the class, or struct, or function, or whatever, where timeOfDay is declared. Commented Mar 17, 2018 at 13:33
  • Just added it. Thanks for taking a look. Commented Mar 17, 2018 at 13:36
  • Related (not a dupe): stackoverflow.com/questions/44604743 Commented Mar 17, 2018 at 14:46

3 Answers 3

2

The compiler is smart enough to figure out that on every possible code path that leads to the first read access of timeOfDay, it is in fact initialized exactly once. Try leaving out one of the assignments as an experiment.

Sign up to request clarification or add additional context in comments.

Comments

1

The compiler let's you declare a let variable without value, but it expects you to set a value for it later. It's possible to not enter on any of the if statements in your example, so the compiler knows that you're trying to read a value that may not exists. You can try a simple if else statement and try to run, just to check :D

Comments

0

Yes, we can declare a Constant without an initial value in Swift. But we need to assign a value later so we can use that Constant, otherwise there would be a compile error. It is also important to note that while we can change the value multiple times in Variables, we can assign a value to a Constant only ONCE.

In the given example above, the if-else statements can only assign a value to the Constant timeOfDay only once. After that, we cannot assign a new value or even create a new if-else statements to change the value of timeOfDay anymore.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.