Android App Development
iOS App Development
Cross Platform App Development
Hire on-demand project developers and turn your idea into working reality.
Big thanks to Webkul and his team for helping get Opencart 3.0.3.7 release ready!
Deniel Kerr
Founder. Opencart
Top Partners
Throughout programming, we get into moments that variable will have no value assigned to it or it could contain a value. We call these variables Optionals in swift programming. Optional binding is a common practice of unwrapping nil values safely.
Let us discuss how the binding process works, by following steps.
Output: We are having coffee
Output: the optionals is nil
Crashing
Sometimes we force unwrap optionals by using an exclamation mark at the end of the variable. In this case, if the optionals have nil value, then it will force the program to crash.
For example:
Which gives EXC_BAD_INSTRUCTION
To avoid these types of crashes, we use optional binding. To unwrap optionals, we can use the exclamation mark “!” or double question mark with a value, the variable will use this value when the optional is nil.
Output: Hello World
if -let statements :
Similarly, we can also use if let statements to unbind the optionals. We can use this to find out whether an optional contains a value. If so, make that value available as a temporary constant or variable.
if let
Output: This is Swift
Guard Statement :
Guard statements are simple and powerful. It checks for some conditions and if it evaluates to be false, then the else statement will execute which will exit the method. This is another way of writing if let statement.
false
else
When 1 is executed, output:
1
Hello John!
Location of John is unknown.
When 2 is executed, output:
2
Hello Jane!
Jane lives in Cupertino
Conclusion
In this blog, we learned about OptionalBinding and safe methods to avoid crashes when unwrapping an optional variable. You can read more about OptionalBinding in swift from here.
You can read more of my blogs from this link.
Your email address will not be published. Required fields are marked*
Name*
Email*
Save my name email and website in this browser for the next time I comment.
Be the first to comment.
We use cookies to personalize your experience. By continuing to visit this website you agree to our use of cookies. Learn more about privacy policy
Excellent work, fast, good quality and understood the brief perfectly! Quick responses developing the project and very good cooperation. I suggest to anyone.
Stathis Plakidas
USA
India
Global
Name
Email
Enquiry or Requirement
If you have more details or questions, you can reply to the received confirmation email.