How to Write and Call Throwing Functions in Swift!

preview_player
Показать описание
Since internet connection 🛜 is never a guarantee, just about every API call requires the use of a throwing function 🤽

❓ But what is a throwing function?

In Swift, a throwing function is a function that might throw an error. In other words, a throwing function might work, but it also might not.

One of the most common use cases for a throwing function is pinging some kind of API. For instance, pinging a weather API to get weather data for a weather app will involve a throwing function. That's because any time you're writing any code that requires an internet connection, there are quite a few things that could keep that code from working as expected, such as:

1️⃣ The user has no internet connection
2️⃣ The user has a poor internet connection
3️⃣ The URL for the API call was invalid for some reason
4️⃣ The server for the API is down

Regardless of the situation, your app needs to be able to "catch" these errors and handle them appropriately, as opposed to silently failing and leaving your user in the dark. Luckily this is a lot simpler than it sounds! 🤓

The most common way to call a throwing function is to use the "try" keyword before the function call, and wrap the function call in a "do catch" block like this:

do {
try doSomeWork()
} catch {
errorMessageIsShowing = true
}

On the other hand, if you're looking to define a throwing function, all you need to do is add the throws keyword to the function definition like this:

func doSomeWork() throws {
// ...
}

🙋‍♂️ Throwing functions were definitely quite confusing to me when I first started iOS development, did you have/are you having the same experience? I'd love to hear from you in the comments!

Follow my other socials here:

#shorts
Рекомендации по теме
join shbcf.ru