Error handling
Optionals
are used to represent the existence/absence of a value. A result of an operation can be optional, so when that operation fails we will receive nil
. The optional itself will not provide any information about how our operation failed and what the cause of the failure, and in most of cases it is useful to know the context and cause of the failure to be able to respond accordingly in our code.
Error handling is the process of responding to and recovering from error conditions in our applications. The Swift standard library provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime.
Let's go through an example to explore the error handling concept. Suppose that we need to read a file and return the content of that file. Using Optionals
, we can develop it as follows:
func checkForPath(path: String) -> String? { // check for the path return "path" } func readFile(path: String) -> String? { if let...