0

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?

Oguzhan Bolukbas
  • 504
  • 6
  • 13

1 Answers1

2

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.

udi
  • 3,672
  • 2
  • 12
  • 33
  • Thanks for your reply. When I run the command `xcrun swift -version` I have obtained the following output: `swift-driver version: 1.45.2 Apple Swift version 5.6.1 (swiftlang-5.6.0.323.66 clang-1316.0.20.12) Target: arm64-apple-macosx12.0` So you are right, it is caused by older Swift version. Many thanks – Oguzhan Bolukbas Aug 29 '22 at 10:25