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 trialFaradja Nondo
1,485 PointsCan we use a guard statement to instantiate an enum? If no why not?
enum HTTPStatusCodes: Int {
case Continue = 100
case Success = 200
case Unauthorized = 401
case Forbidden = 403
case NotFound = 404
}
let statusCode = 200
if let httpCode = HTTPStatusCodes (rawValue: statusCode) {
print(httpCode)
}
How can I use a guard statement instead on httpCode? Or is guard only to be used within an enum, struct, function or class?
1 Answer
jcorum
71,830 PointsGuard gets tricky. Here's an example that works, but it is in a function:
func returnStatusText(statusCode: Int) {
guard let httpCode = HTTPStatusCodes(rawValue: statusCode) else {
print("error")
return //return invalid outside of a func
}
print(httpCode)
}
returnStatusText(202) //prints "error"
returnStatusText(200) //prints "Success"
Apple says:
The else clause of a guard statement is required, and must either call a function marked
with the noreturn attribute or transfer program control outside the guard statementβs
enclosing scope using one of the following statements:
return
break
continue
throw
break is only allowed inside a loop, if, do, or switch.
continue is only allowed inside a loop.
throw is OK in a function, but requires the function to throw an error.