Short version:
Am I correct that conditional expressions were added in 5.9 (September of 2023) and were not available in 5.7?
Full version:
Documentation includes the following:
let temperatureInCelsius = 25
let weatherAdvice: String
if temperatureInCelsius <= 0 {
weatherAdvice = "It's very cold. Consider wearing a scarf."
} else if temperatureInCelsius >= 30 {
weatherAdvice = "It's really warm. Don't forget to wear sunscreen."
} else {
weatherAdvice = "It's not that cold. Wear a T-shirt."
}
print(weatherAdvice)
// Prints "It's not that cold. Wear a T-shirt."
That works fine. This example code is immediately followed with:
Here, each of the branches sets a value for the `weatherAdvice` constant, which is printed after the `if` statement.
Using the alternate syntax, known as an `if` expression, you can write this code more concisely:
let weatherAdvice = if temperatureInCelsius <= 0 {
"It's very cold. Consider wearing a scarf."
} else if temperatureInCelsius >= 30 {
"It's really warm. Don't forget to wear sunscreen."
} else {
"It's not that cold. Wear a T-shirt."
}
print(weatherAdvice)
// Prints "It's not that cold. Wear a T-shirt."
Clearly, this code is incomplete as written and needs to have the first two lines (the declarations for temperatureInCelsius and weatherAdvice) prepended. No worries. However, when I add those lines the code fails to compile. The errors I get are:
test.swift:4:21: error: expected initial value after '='
let weatherAdvice = if temperatureInCelsius <= 0 {
^
test.swift:4:20: error: consecutive statements on a line must be separated by ';'
let weatherAdvice = if temperatureInCelsius <= 0 {
^
;
test.swift:5:5: warning: string literal is unused
"It's very cold. Consider wearing a scarf."
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test.swift:7:5: warning: string literal is unused
"It's really warm. Don't forget to wear sunscreen."
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test.swift:9:5: warning: string literal is unused
"It's not that cold. Wear a T-shirt."
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I'm including the output from the command-line attempt because it includes the line numbers but when I try this code in XCode I get the same errors inline.
After a lot of pounding my head and wondering if the docs are simply wrong, I thought to check my version numbers.
macOS: 12.6.8 (21G725)
XCode: Version 14.2 (14C18)
$ swift --version
swift-driver version: 1.62.15 Apple Swift version 5.7.2 (swiftlang-5.7.2.135.5 clang-1400.0.29.51)
Target: x86_64-apple-macosx12.0
Further searching shows the revision history which refers to the docs being updated to include conditional expressions for the 5.9 update. Am I right that this is the problem?