Swift Nested If

Swift Nested If

Nest if statements to check multiple levels of conditions.


Use nested conditions for multi-step checks

Use nested conditions to handle layered checks, such as authentication then role.

Example

let isLoggedIn = true
let isAdmin = false
if isLoggedIn {
if isAdmin {
  print("Admin panel")
} else {
  print("Limited access")
}
}

Use nested conditions to handle layered checks, such as authentication then role.



Validate and Branch

Validate inputs first, then use a nested if to branch inside the valid case.

Example

let score = 85
if score >= 0 && score <= 100 {
  if score >= 90 {
print("A")
} else if score >= 80 {
print("B")
} else if score >= 70 {
print("C")
} else {
print("Below C")
} } else { print("Invalid score") }

Comments

Leave a Reply

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