Advanced Error Handling in Swift 5

Advanced Error Handling in Swift 5

try? try! and try Advanced Error Handling in Swift 5

In Swift, there are many ways to handle errors. In this article, I am going to deeply explain how to handle errors using throwable functions. If you are familiar with JSONDecoder(), then you have seen the below code before. do { try JSONDecoder().decode(MyStruct.self, from: someData) } catch let error { print(error) } This is called Do-Catch block, where we are forced to use it otherwise Xcode will complain and won’t compile and gives us this error: “Call can throw, but it is not marked with ‘try’ and the error is not handled” That’s because the method decode(_:) is a throwable which means it might throw an error and we can’t handle it like a normal function. To have a better understanding of the difference between try, try!, and try? let’s design our own throwable method. Say we have to design a system that allows people to ride a Roller Coaster and our requirements are that the rider cannot be shorter than 120 cm and not taller than 210 cm. First thing we do we need to write an enum and conform it to the Error protocol. enum RiderHeightError: Error { case tooShortToRide case tooTallToRide } Then let’s create a computed property that describes our error cases. enum RiderHeightError: Error {

case tooShortToRide
case tooTallToRide
var description: String {
    switch self {
    case .tooShortToRide:
        return "You are shorter than 120 cm, try next year."
    case .tooTallToRide:
        return "You are taller than 210 cm, try another game."
    }
}

} Now we have our enum with the error cases ready, let’s write a throwable function. func safetyCheck(riderHeight: Int) throws {

if riderHeight < 120 {

    throw RiderHeightError.tooShortToRide

} else if riderHeight > 210 {
    throw RiderHeightError.tooTallToRide
} else {
    print("You are good to go. Have fun.")
}

} Now we’ve created a function called safetyCheck(). It has one parameter which is the rider’s height. The function checks twice on the rider’s height to make sure it complies with the safety rules. You noticed that we used two new keywords “throws” and “throw”. The difference between both is pretty simple. “throws” means this function is throwable and in order to use it, you have to write try before the function. “throw” means that something went wrong and a specific error has to be thrown. Basically there are three ways to call a throwable function. First way is to write Do-Catch block which is the recommended way to handle the errors. do { try safetyCheck(riderHeight: 110) } catch let riderError { if let error = riderError as? RiderHeightError { print(error.description) } } => You are shorter than 120 cm, try next year. We see that we caught the error and we also got a clear description of the error. There are many ways to write the catch block. The next example I’ll show another way to do it. do { try safetyCheck(riderHeight: 230) } catch RiderHeightError.tooShortToRide { print("Too Short To Ride The Roller Coaster") } catch RiderHeightError.tooTallToRide {

print("Too Tall To Ride The Roller Coaster")

} => Too Tall To Ride The Roller Coaster Second way is to use “try?” instead of Do-Catch block. It will reduce a few lines of code, but it won’t give you what exactly went wrong. It will give you nil instead if an error was thrown. try? safetyCheck(riderHeight: 100) => nil

swift-programming swift error error-handling ios-app-development ios

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.

Hire iOS App Developer

Are you looking to transform your idea into an iPhone application? Hire iPhone programmer team from **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")** to ensure the best results, utilizing all the latest trends in iOS app...

iOS(iPhone OS) App Development Services

Skenix Infotech is a leading iPhone app development company with skilled & expert iOS app developers. Hire us to get affordable iPhone app development services.

Top iOS Mobile App Development Agency in New York

Are you looking for a [Top iOS Mobile App Development Agency in New York]**(https://www.appcluesinfotech.com/ios-app-develop**ment-company/ "Top iOS Mobile App Development Agency in New York") for your app projects? Then AppClues Infotech is the...

Custom iOS App Development Company New York

Hire the best iOS mobile app development company in New York, AppClues Infotech specialized in custom iOS app development and design services.