In this post, Let’s see what happens If we forced unwrap things and the crashes that it creates.
    Let me take 3 simple classes.
    1. User
    2. UserAccount
    3. WishList
    Here I want to check the account of the user. Then only we need to check the wish list of the user and notify if items are available in the wish list.
    I am creating user instance and passing it to a function which checks user’s account first and then wish list and then notifies the user on items availability.
    First, I need to check user’s account optional value.
    What If we forced unwrap and access user’s account object.
    Application gets crashed with a fatal error.
    fatal error: unexpectedly found nil while unwrapping an Optional value
    This is because, we haven’t assigned UserAccount object for user.
    I am assigning it now.

    If we run the app, It will not get crashed. To avoid this crash, What we can do is, We can check with If let as shown below

    Like this we are checking the optional user account object and proceeding only if the value is not nil.
    For checking a single object is fine using If lets. What If we have chain of objects need to be checked like in our example.
    1. User’s account should be checked
    2. User’s wish list object should be checked
    In handling chain of optional objects, guard helps a lot in checking all the optional nil conditions in a single statement and returning the function execution If any of the optionals are nil.
    Let me show you how.

    Recent Articles

    Amazon Echo Buds Review

    Amazon isn’t usually one for following the crowd, but even this retail giant couldn’t ignore the impact of Apple's AirPods. Apple’s true wireless earbuds...

    Apple AirPods 2 vs AirPods Pro: which is better?

    If you're in the market for a pair of new wireless earbuds and you also happen to own an Apple smartphone or tablet, chances...

    A2Hosting Review 2019 | An Affordable Hosting for Newbies | 100% Genuine Review

    I'm using A2Hosting since November 2018. Based on personal experience, I have written this article. Saying your hosting provider as the backbone of your online...

    Alphabet, Amazon, Apple, Netflix See Shares Dim in Eyes of Investors

    Technology companies that catapulted Wall Street to glorious heights have seen shares tumble on investor concerns that the days of stellar profits are waning. Since...

    Apple Upstages Amazon in Selecting New Tech Hub Locations

    One tech giant strung dozens of North American cities through a circus-like contest that led mayors and governors to desperately pitch their regions -...

    Related Stories

    Leave A Reply

    Please enter your comment!
    Please enter your name here

    Stay on op - Ge the daily news in your inbox