if vs if let vs guard let in Swift

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.

if condition

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

if colors.contains("red") {
print("red is present in palette")
}
let colors = ["red", "green", "blue"]

if colors.contains("red") {
print("red is present in palette")
} else {
print("red is not present in palette")
}
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

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")
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/

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store