Swift 2 introduced the guard
keyword, which could be used to ensure that various data is configured ready to go. An example I saw on this website demonstrates a
From Apple documentation:
Guard Statement
A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.
Synatx:
guard condition else {
statements
}
Advantage:
1. By using guard
statement we can get rid of deeply nested conditionals whose sole purpose is validating a set of requirements.
2. It was designed specifically for exiting a method or function early.
if you use if let below is the code how it looks.
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error == nil {
if let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 {
if let data = data {
//Process Data Here.
print("Data: \(data)")
} else {
print("No data was returned by the request!")
}
} else {
print("Your request returned a status code other than 2XX!")
}
} else {
print("Error Info: \(error.debugDescription)")
}
}
task.resume()
Using guard you can transfer control out of a scope if one or more conditions aren't met.
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
/* GUARD: was there an error? */
guard (error == nil) else {
print("There was an error with your request: \(error)")
return
}
/* GUARD: Did we get a successful 2XX response? */
guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {
print("Your request returned a status code other than 2XX!")
return
}
/* GUARD: was there any data returned? */
guard let data = data else {
print("No data was returned by the request!")
return
}
//Process Data Here.
print("Data: \(data)")
}
task.resume()
Reference:
1. Swift 2: Exit Early With guard 2. Udacity 3. Guard Statement