John John - 2 days ago 5
Swift Question

How to convert Nested if statements ( with else clause ) in a single if statement in Swift?

It is easy to convert nested if statements into single if statements but my question is is there a way to do this with if statement including else clause? (Note: I know guard statement is a way to do this)

Here is example : This example converted into single if statement.

Nested if statements into single without else statements

if let firstNumber = Int("4"),
let secondNumber = Int("42"),
firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}
// Prints "4 < 42 < 100"

if let firstNumber = Int("4") {
if let secondNumber = Int("42") {
if firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}
}
}
// Prints "4 < 42 < 100"


How do I convert this example into single statement?

NOTE: This example has 3 else clause for that reason I can not convert it into single if statement as I did above.

if let firstNumber = Int("4") {
if let secondNumber = Int("42") {
if firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}else{do something}
}else{do something}
}else{do something}

Answer

Actually remove the inner ifs and the replace the braces with commas

if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
    print("\(firstNumber) < \(secondNumber) < 100")
} else {
  // do something else 
}

A single if statement can have only a single else clause.

Comments