if vs if let vs guard let in Swift

if let and guard let are two conditional operators or condition checker which make our life super easy. Other languages have only if as condition checker but swift provides if let as well as guard let also which are operationally the same but a bit different in functionality.

This post was originally posted at https://agrawalsuneet.github.io/blogs/if-vs-if-let-vs-guard-let-in-swift/ and reposted on Medium on 16th Mar 2021.

To understand their differences, let’s try to understand what they are in details first.

if condition

Normal if condition is nothing but to check whether a condition is true or not.

let colors = ["red", "green", "blue"]

if colors.contains("red") {
print("red is present in palette")
}

This can be clubbed with else and else if but both of them are optional.

let colors = ["red", "green", "blue"]

if colors.contains("red") {
print("red is present in palette")
} else {
print("red is not present in palette")
}

we can even club multiple if conditions with simple && or || operators based on the use case.

let colors = ["red", "green", "blue"]

if colors.contains("red") || colors.contains("green") {
print("red or green are present in palette")
} else {
print("red and green both are not present in palette")
}

if let

Now let’s think about someplace where we want to compute something and based on the computed value we need to put an if condition.

let colors = ["red", "green", "blue"]

let index = colors.firstIndex(where: {$0.elementsEqual("green")})

if index != nil {
print("green is present in palette at position \(index ?? -1)")
} else {
print("green is not present in palette")

We are trying to check if an element is present in an array and if present we are trying to print its position.

The same code can be replaced with if let instead of if condition.

let colors = ["red", "green", "blue"]

if let index = colors.firstIndex(where: {$0.elementsEqual("green")}) {
print("green is present in palette at position \(index)")
} else {
print("green is not present in palette")
}

Please continue reading at https://agrawalsuneet.github.io/blogs/if-vs-if-let-vs-guard-let-in-swift/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.