Swift If…Else

Swift If…Else

Control the flow of your program with ifelse if, and else.

Combine conditions with logical operators.


Basic If…Else

Use if to run code when a condition is true.

Add else for the false case, and else if for multiple branches.

Example

let score = 82
if score >= 90 {
  print("A")
} else if score >= 80 {
  print("B")
} else {
  print("C or lower")
}

This example prints a letter grade based on the score.

Tip: Swift conditions must be Bool.

There is no implicit conversion from integers to booleans.



Even or Odd

Use else to handle the alternate outcome.

Example

let n = 7
if n % 2 == 0 {
  print("Even")
} else {
  print("Odd")
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *