By using optional chaining we are calling properties,methods and subscripts on an optional that might currently be nil.
Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.
It will return two value
1. nil - if the optional contains a 'nil' value all its its related property, methods and subscripts returns nil
2. Actaul value: if the optional contains a 'value' then calling its related property, methods and subscripts returns values
For Example:
If the one School has one ClassRoom class optional properties and in the ClassRoom class has one property that is numberOfStudent. if there is any case where are tring to access numberOfStudent from School class ClassRoom properties but the ClassRoom property is nil and if we used forced unwnwrapping then it will create runtime error to avoid this we will use optional chaining. So we can called Optional Chaining as an best Alternative to Forced Unwrapping.
class School {
var classRoom: ClassRoom?
}
class ClassRoom {
var numberOfStudent = 1
}
var sulakeSchool = School()
// Forced Unwrapping.
print(sulakeSchool.classRoom!.numberOfStudent)//Fatal error: Unexpectedly found nil while unwrapping an Optional value:
//Optional Chaining
print(sulakeSchool.classRoom?.numberOfStudent)
//Print nil on console
//calling method
class ClassRoom {
var numberOfStudent = 1
func display(){
print(numberOfStudent)
}
}
print(sulakeSchool.classRoom?.display())
////Print nil on console
//Accessing Subscipt
class ClassRoom {
var students = [Student]()
var numberOfStudent = 1
func display(){
print(numberOfStudent)
}
subscript(index:Int)-> Student{
get{
return students[index]
}
set{
students[index] = newValue
}
}
}
print(sulakeSchool.classRoom?[0])
////Print nil on console