Today we will be discussing ”?”,”!” and the terms which are related to those in programming.
What do we know about nil values? They are the values which they don’t have anything. We can see that as a null which does mean “0” in some other languages. It does mean “nothing”, non-existent”.
Let’s start with “?”;
In the Swift programming language, we have this term “optional”. We cannot know our value will return any value to us and we will use the question mark to check if it has any value or is it null. Null values are not allowed in Swift, that’s why we should use optionals. So it means our type, value, a variable could be equal to some value or it is not equal to anything else. If its value is nil that means our variable is optional otherwise it is not something possible.
Just a reminder Int and Int? is a different type that you can’t even add to each other.
For example, I can create an integer like below, I will get nil because my variable is not initialized to anything.
So, now we know why we use question mark but not everything is easy like how it looks. We are gonna need some other spice to use this question mark and now we have a brand-new term “unwrapping” and let’s get to know “!”. If our variable has a nil value we had to unwrap them.
We change our Optional value to normal value with unwrapping to get rid of an optional keyword.
We call Force Unwrapping when we use “!” and when we check if it is nil or not, it will just respond to us with the keyword “optional” but if we use “!” to force unwrap we will get rid of the optional type of value we will get the normal type of value.
We can use directly “!” exclamation mark instead of question mark. We won’t need to use any other exclamation mark . Just like you see in the example below.
If we want to use Implicit Unwrapping it is like promising the compiler I will define a value for sure this variable won’t be nil I promise. So we don’t have to unwrap the value.
In short if we use ? ; it means, just checking if it has a value or will it be a nil value.
If we use ! it means I promise my variable will get a value it won’t be nil and our compiler is happy now. If we use “!” if we unwrap the value and if there is no value our code will crash and we will get a run time error.
It is same like Force Unwrapping ,We will change our Optional variable to normal type.
It is all for now I hope you liked.Have a nice techy dayss:)))