feat(guide): Explained the difference between declaring & assigning a constant in Swift (#18515)

Added a code snippet to explain the difference between _declaring_ a constant and _assigning_ a value to it.
pull/18548/merge
Marwan Alani 2018-10-14 12:26:14 -04:00 committed by Quincy Larson
parent 5cbe21754a
commit 1d5fed62f1
1 changed files with 10 additions and 1 deletions

View File

@ -14,7 +14,16 @@ You declare constants with the `let` keyword then give it a name `name` then you
Once you have declared a constant you don't need to use the `let` keyword anymore you just call it by its name.
The value of a constant cant be changed once its set.
The value of a constant cant be changed once its _set_. With that being said, it is important to note that the Swift compiler is smart enough to understand the difference between _declaring_ a constant, and _assigning_ a value to it. Consider the following code snippet:
```swift
let shouldWaterFreeze: Bool // (1)
if temperature < 0 {
shouldWaterFreeze = true // (2)
else {
shouldWaterFreeze = false // (3)
}
```
The snippet above is valid and compiles with no problems (given that we have declared and assigned an `Int` value to `temparature` somewhere earlier). Notice that we _declare_ the constant in (1), and then _assign_ a value to it (2) or (3).
#### More Information:
- <a href='https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#ID310' target='_blank' rel='nofollow'>The Swift Programming Language</a>