This tutorial is for those iOS developers who still thinks that we can write only return in a guard else 😀
Here are the rules.
- We can write return in a guard else only inside of a function/method
- We can write break in a guard else only inside a loop (if, do, or switch)
- We can write continue in a guard else only inside a loop
Let’ see this with an example for better understanding.
I am taking 2 classes, Fruit & dessert (There is no difference b/w those 2 classes. Sorry about that )
class Fruit {
var name: String
var price: Int
init(name: String, price: Int) {
self.name = name
self.price = price
}
}
class Dessert {
var name: String
var price: Int
init(name: String, price: Int) {
self.name = name
self.price = price
}
}
I am taking an array of items.
let apple = Fruit(name: "apple", price: 1)
let banana = Fruit(name: "banana", price: 2)
let icecream = Dessert(name: "icecream", price: 2)
let items = [icecream, apple, banana] as [Any]
I need to check whether items is having all Dessert objects or not.
So, I need to write a loop and break it immediately If I find a Fruit. Cause, If there is at least a fruit, It’s not a collection of all Desserts.
var allDesserts = true
for obj in items {
guard let _ = obj as? Dessert else {
allDesserts = false
break
}
}
if allDesserts {
print("All are desserts!")
} else {
print("There are fruits as well")
}
This is the use case of using break in guard else
Let’s see the use case of a continue in guard else.
I need to know number of fruits that are there in items. So I take a counter and increment it If the object is not a Fruit.
var numberOfFruits = 0
for obj in items {
guard let _ = obj as? Dessert else {
numberOfFruits = numberOfFruits + 1
continue
}
}
numberOfFruits //2 apple & banana
That’s how we can leverage guard else in loops and can use break and continue as well with return.
But, We need to stick to the rules, otherwise we will end up with build error.
- We can write return in a guard else only inside of a function/method
- We can write break in a guard else only inside a loop (if, do, or switch)
- We can write continue in a guard else only inside a loop
//error: return invalid outside of a func
// error: 'break' is only allowed inside a loop, if, do, or
switch
// error: 'continue' is only allowed inside a loop
Hope this post is useful. Feel free to comment incase of any queries.
No comments:
Post a Comment