Sunday, 7 May 2017

Working with Optional Chaining in Swift

Optional chaining is process for querying and calling properties, methods, and  subscripts on an optional that might  be currently nil. If the optional contains a value then call to properties, methods or subscript will success otherwise call will return nil if any optional is nil in the calling chain.

Optional chaining is alternative to forced unwrapping.  In forced unwrapping we place an exclamation mark(!) after the optional value to force the unwrap of its value.

But in optional chaining we put the question mark(?) after the optional value . The main difference between forced unwrapping an optional chaining is that  in forced unwrapping if optional doesn't have a value then we get a run time error. But in optional chaining if optional doesn't have value means it's nil then it gracefully returns nil?.(optional nil).

A point to remember about optional chaining is that if we are accessing properties, calling methods or accessing subscripts , they all return nil? if optional chaining fails at any levels.

 The result of optional chaining call is of the same type as the expected return value, but wrapped in an optional.

Example :

     class MyClass{

     var  address:Address?
}

class Address{

  var streetName =  "12A Arthur Road"
}


let myClass  =  MyClass()

First we are accessing the  with forced unwrapping:

let address = myClass.address!.streetName

This call will give a run time error because currently the value of address is nil in MyClass.

Now with optional chaining :
 let address = myClass.address?.streetName

This call will end gracefully because with optional chaining if it fails at any level it returns nil. It is same as calling nil in objective C.

1 comment:

  1. Hai Good information shared about IOS. Keep sharing updated ios tutorials. This blog post is really helpful.

    ReplyDelete