Consecutive statements on a line must be separated by ';'

While following the swift tour documentation i came across this block of code which is supposed to conditionally return a value, then gets stored in a variable. But then the compiler throws me an error.

Consecutive statements on a line must be separated by ';'

my code :

var teamScore = 0

for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}

let scoreDecoration = if teamScore > 10 {
    "🎉"
} else {
    ""
}
print("Score:", teamScore, scoreDecoration)

Screenshot

Answered by Claude31 in 754924022

You cannot add the if as you did.

But you can replace with so called ternary operator:

let scoreDecoration = teamScore > 10 ?  "🎉"  :  ""

If you do want to use the if, create a computed var:

var scoreDecoration : String {
   if teamScore > 10 {
    return "🎉"
  } else {
     return  ""
  }
}
Accepted Answer

You cannot add the if as you did.

But you can replace with so called ternary operator:

let scoreDecoration = teamScore > 10 ?  "🎉"  :  ""

If you do want to use the if, create a computed var:

var scoreDecoration : String {
   if teamScore > 10 {
    return "🎉"
  } else {
     return  ""
  }
}

Hi, you can do that :

let scoreDecoration: String
if teamScore > 10 {
    scoreDecoration = "🎉"
} else {
    scoreDecoration = ""
    
}

Or use ternary operator :

let scoreDecoration = teamScore > 10 ? "🎉" : ""

What version of Xcode are you using? Note that using if as an expression is new in Swift 5.9 and requires Xcode 15. If you are in Xcode 14 or earlier, then you can use one of the solutions given above.

Unfortunately the default language book on Swift.org is for 5.9 already and I can’t even find an older version.

Using if as an expression is new in Swift 5.9. If you’re using Xcode 14.3 or earlier, rather than the Xcode 15 beta released earlier this week, you won’t be able to use this new syntax.

It is a problem with the Swift Version

It looks like you didn't update your Swift.

In the Version Compatibility documentation, Apple notified the book is describing Swift 5.9.2.

Go to the App Store, and update your XCode to update the Swift version.

Consecutive statements on a line must be separated by ';'
 
 
Q