As we learned in my other blog about Initializers in Swift Programming Language that every variable in Swift should be initiazed before trying to access the value.
So what if you do not want to initialize a variable. That is where Optionals in Swift comes into play.
Before start discussing about Optionals you should know about nil. nil in Swift means nothing, no value at all.
Lets see what optionals provides us:
So what if you do not want to initialize a variable. That is where Optionals in Swift comes into play.
Before start discussing about Optionals you should know about nil. nil in Swift means nothing, no value at all.
Lets see what optionals provides us:
- Optionals can store value nil which means no value.
- Any non optional can not store nil.
- you can check for options have nil or value by just writing if value no need to add extra code for == nil. because optionals can be used in boolean context.
Reading a value from the Optional is called unwrapping the Optional.
How to unwrap optionals?
- using the force unwrap operator !. but if you use this operator without checking for nil you may end up with an error at runtime.
- using the if let statement you can check for the value and unwrap it once. This is called optional binding.