Fairly experienced coder here. Here is some Swift code in a playground:
var word : String? = "Hello, World!"
if let word {
print("it is a \(word)")
}
else {
print("The word is not assigned")
}
It prints out "it is a Hello World"
I know the code doesn't make much sense but I've seen the pattern in tutorials I'm following. I understand what's going on if I change the first 'var' to a 'let' if the constantName following the 'let' is declared with 'let'. The Swift 5.7 book says 'word' must be a constantName. So I'm thinking "if let word" creates a new var with scope only in the if statement - so how does it know the contents of the other variable named 'word' and declared as a 'var'.
The code does make sense, actually. if let word
unwraps the outer variable word (which is an optional), making inner word (i.e. within the true component of the if) a non-optional string.
You should be able to prove this by adding print("it is a \(word)")
between the var and if (and again at the very end of your code), which will then print the wrapped word.
Another way to think of this is that if let word
is shorthand for if let word = word
.