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.