POV | Difference between ! and ? | In-Shorts Story

Whenever we write code in Swift we use optional because it beautiful way for handling null values as in Objective C its little different and difficult as well, one of the reason is, Objective C based on C, so there are legacy issues as well, but in Swift there is not legacy at all so for handling null value we have separate feature from the language itself that is called Optional (Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil).

Now the second question comes up in mind is, how does it work?

The idea is whenever you feel any value could be nil in future just make it as Optional simply and before using it first see, is it contains anything? if Yes than use it otherwise make the nessarary decision. In other words, we can say its something like you has a box and it may or may not contains something so before using it first unwrap and check.

How to create Optionals?

? and ! here is the answer. I also googled what is the correct difference and where to use what but only a few links were useful. Small answer is.

Use ? if the value can become nil in the future so that you test for this before using always (we have to use if let or guard statement).

Use ! if it really shouldn’t become nil in the future, but it needs to be nil initially like we do with IBOutlets always (Benefit is before using no need to unwrap using if let or guard statement). But it we use ! and the value is nil ready for the crash.

Thank you for reading.
Please share your comment it will help me to improve.

Happy Learning.

2 thoughts on “POV | Difference between ! and ? | In-Shorts Story

  1. Hi Bunty M
    Great post, diff b/w ‘?’ & ‘!’ is clearly explained. I think it would be great if you can explain the stuff using some example code or show some snapshots. That would really help beginners to understand.
    All the best (Y)

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s