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.
Optional Binding
How this optional binding works?
- First it checks whether the provided value is optional or not.
- If it is optional it checks if its value is nil.
- If value is not nil it will assign the value to the variable on the left side.
Optional Chaining
Lets say we have three classes
Person, Residence and Address.
Person have Optional Residence and Residence and Optional Address and Address have Optional buildingNumber
int addressnum = paul.residence?.address?.buildingNumber?.toInit()
- It works with any type.
- The chaining operator ? checks if the thing to its left is nil or present before proceeding to the next value in the chain.
- If any of the value is nil during the evaluation of the expression it will return nil and will not evaluate the rest of the expression.
- we can combine the optional chaining and the optional binding together like
if let addressNumber = paul.residence?.address?.buildingNumber?.toInit() {
addNumber(addressNumber)
}
What actually optional is?
It is nothing but a generic enum.
enum Optional<T>{
case None
case Some(T)
}
So as we have discussed optionals what is it that Optionals provide us?
- It provides us the SAFE way of programming.
- Missing values are nil and present values are wrapped up in the optional.
- If a type is not optional than it must have a value because it can’t be nil.
This is brief intro to Optionals...
Happy Coding....
No comments:
Post a Comment