Error-Proof Your Swift App: A Step-by-Step Guide
When building a mobile app, error handling is crucial to ensure a seamless user experience. In this tutorial, we’ll explore how to detect and resolve errors in a simple bookstore application built using Swift.
Getting Started
To begin, make sure you have:
- Familiarity with Swift programming
- Xcode installed on your local machine
- Online Swift Playground for Windows users
Setting Up the Project
Create a blank Xcode playground by opening an Xcode application and selecting Empty in the Other tab. Then, create a new playground file inside the newly created directory and name it. Modify the default code to the code below and click the Play button to ensure the code is running:
swift
print("Hello, playground")
Building the Bookstore App
Our bookstore app requires two classes: User
and Item
. The User
class contains the user’s name and available balance, while the Item
class contains the name of the book, price of the book, and the quantity of the book left in the store.
Error Test Cases
Two major issues can arise in this application:
- What if the user’s wallet balance can’t afford a book in the store?
- What if the quantity of books in the store is less than the amount the user wants to purchase?
Let’s test our current code with these test cases individually.
Price Error
If we set the user’s wallet balance to $500 and try to purchase $1000 of Oliver Twist book copies, the console prints an error message. Instead of deducting the total book price from the user’s wallet, we must print an error message when the user’s wallet balance is less than the book price.
Quantity Error
Another test case is when there are fewer books in the store than books needed by a user. If we set the quantity of the Oliver Twist book in the store to 0 and then call the purchaseBookFromStore
function to buy 1 book, the console prints an error message.
Handling Errors
To fix these error cases, let’s write a condition to check whether the user can afford this book and whether the quantity of the book available is less than the quantity required by the user. If the user cannot afford the book or there is not enough quantity of the book, we can throw an error.
Throwing a Defined Error
With the current state of our application, the function is not throwing the appropriate error to tell us what went wrong. To do this, we must define custom errors that we want to throw using a Swift enum, which conforms to the built-in Swift error class.
Catching Errors
Now, we can catch the individual errors like so:
swift
do {
try purchaseBookFromStore(user: user1, item: storeItem)
} catch BookstoreError.insufficientFunds {
print("Insufficient funds")
} catch BookstoreError.outOfStock {
print("Out of stock")
} catch {
print("An unknown error occurred")
}
By handling errors and displaying custom errors, we can understand why they occur and solve issues faster.