Control Flow III
guard statement
Control Flow III
guard statement
0
0
Checkbox to mark video as read
Mark as read

If we want to avoid nesting our code with multiple if statements, we can use guard instead. guard will check a condition in the same way, but stoping the code when the condition is not met.

var shoppingList: [String] = [
    "Potato",
    "Tomato",
    "Chicken",
    "Salmon"
]

func removeAt(index: Int) {
    guard index < shoppingList.count else {
        return
    }

    shoppingList.remove(at: index)
}	

guard let

if let can be also replaced with this new statement.

func sayMyName(name: String?) {
    guard let unwrappedName = name else {
        return
    }

    print(unwrappedName)
}

You can shorten this using the same name for the unwrapped value:

guard let name else {
	return
}

You can use other keywords instead of return, like throw.

guard let name else {
	throw NSError()	
}

course

Quiz Time!

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy