Exploring error handling
Things don't always go as you would expect, so you need to keep that in mind as you write apps. You need to think of ways that your app might fail, and what to do if it does.
Important information
For more information on error handling, visit https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html.
Let's say you have an app that needs to access a web page. However, if the server where that web page is located is down, it is up to you to write the code to handle the error, such as trying an alternative web server or informing the user that the server is down.
First, you need an object that conforms to Swift's Error
protocol:
- Type the following code into your playground:
enum WebpageError: Error { case success case failure(Int) }
This declares an enumeration,
WebpageError
, that has adopted theError
protocol. It has two values,success
andfailure(Int)
. You...