Optional Chaining



Apple says "Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil". While processing if optional has value then the process will succeed otherwise the process will return nil.

This querying, calling properties, methods and subscribe can be chained together and it failed gracefully if chain returns nil.

An Alternative to Forced unwrapping: you will add question mark '?' after the optional value on which property you will wish to call properties, method, and subscripts if the optional is non-nil.

Could an important interview question - The main difference between optional chaining and forced unwrapping is optional chaining fails gracefully whereas forced unwrapping will give runtime error when the optional value is nil.

The result of optional chaining will return the same type value but that value will be wrapped with optional. So if Int is return type when querying through optional chaining will return Int?

class Company {
    var address: Address?
}

class Address {
    var headOfficeAddress = 1
}

let myComp = Company()

let roomCount = myComp.address!.headOfficeAddress // run time error when myComp
// will be nil

//safe way to access adresss
if let adresss = myComp.address?.headOfficeAddress {
    print("Company address is \(adresss)")
} else {
    print("Unable to retrieve the head office address.")
}
So given difference above explains through above code snippet.

Now we will get know about the accessing properties using calling a method

class Company {
    var address: Address?
}

class Address {
    var headOfficeAddress:String = "Bangalore"
}

var myComp = Company()

let headOff = createAddress()
myComp.address = headOff

if let adresss = myComp.address?.headOfficeAddress {
    print("Company address is \(adresss)") //Company address is Bangalore, Karnataka\n"
    
} else {
    print("Unable to retrieve the head office address.")
}

func createAddress() -> Address {
    
    print("Function was called.")
    let someAddress = Address()
    someAddress.headOfficeAddress = "Bangalore, Karnataka"
    return someAddress
    
}
If "address" optional value will nil then createAddress() will not be called otherwise it will print the address. So same way you can get the idea of accessing method, subscript etc.


Hope above points will be clear now. Please, check the privous post about the Optional. Let me know your inputs.

Comments

Popular posts from this blog

Copy Vs Mutable Copy in iOS

How to Disable iOS/iPad App availability on Mac Store, Silicon?

Closures in Swift - Part 1