in Swift documentation at https://docs.swift.org/swift-book/GuidedTour/GuidedTour.html, there are examples about usage of optionals and unwrapping them. When I try the examples on my Macbook, I got an error as; "Variable binding in a condition requires an initializer".
Defining the variables part in document:
let nickname: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickname ?? fullName)"
Explanation and example parts which throws the error written above:
You can use a shorter spelling to unwrap a value, using the same name for that unwrapped value.
if let nickname {
print("Hey, \(nickname)")
}
Why I cannot use if let nickname and if it throws error, why it is written in the documentation?
The shorthand syntax for optional unwrapping with if let, guard let and while let was introduced in swift 5.7. I believe u are using an older version of swift.
Check this to find out which version of swift u are using.
For more details read the section Language updates -> Quality of life improvements.