Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialtmsmth
10,543 Pointsusing guard
In the helper method video for the story app, Pasan wrote :
guard firstChoice != nil && secondChoice != nil else { return page }
For me, this means that if one of two is nil or both are nil then return page but if both are not nil then don't go to the else clause.
But in the video, Pasan uses this saying 'if both are not nil then return page' so i'm confused !
tmsmth
10,543 PointsWould make more sens, thanks !
1 Answer
Jhoan Arango
14,575 PointsHello,
The guard statement is for an early exit. "You use the guard statement to require that a condition must be true in order for the code after the guard statement to be executed."
So in your example, if firstChoice and secondChoice have a value, then it may continue executing the code, other wise then return the "page".
Technically we are "guarding" to make sure that there is a value before continuing the execution, if there is no value then we stop the execution and return something.
Consider the following example:
var user: String?
func checkIfUserExist(){
// if "user" has no value it will execute the code inside the else clause, and exit the scope
guard user != nil else { print("User is nil"); return }
// If "user" has a value it will execute this code
print("user is not nil")
}
checkIfUserExist()
hope this helps
Taylor Smith
iOS Development Techdegree Graduate 14,153 PointsTaylor Smith
iOS Development Techdegree Graduate 14,153 PointsI don't remember the video all that well, but it sounds like the code should look like this:
guard firstChoice != nil && secondChoice != nil else {
// do something here if one or both ARE nil }
return page
maybe "return page" was not suppose to be in the else brackets