I'm working on Apple's "Start Developing iOS Apps with Swift" tutorials. So far the code makes sense, except for line # 4 below where we are accessing UIImagePickerViewController to select an image from the user's photo library...
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("Expected a Dictionary with an image, was provided: \(info)")
}
photoImageView.image = selectedImage
dismiss(animated: true, completion: nil)
}
What does guard statement do in general and what is it doing in this specific line of code?
Why and when should we use guard?
Hello mkhan094,
The general idea behind a guard statement is to be a "preflight" for the rest of your code. You could do if/then/else structures to do the same thing, but that adds complexity to your logic. If you are just checking for the validity of input statements, it is better to put that into a guard up-front and do an early return. You could use just an "if" statement that returns early. People have done that for years. The "guard" statement is just a formalization of the idea.
This specific guard statement is making sure that the info dictionary has a value for the "UIImagePickerControllerOriginalImage" and ensures that said value is a valid UIImage.
You use a guard to separate your low-level, error-handling boilerplate from your more important code logic.