Javatpoint Logo
Javatpoint Logo

Swift Optional Chaining

Optional Chaining is process which is used to call properties, methods, and subscripts on an optional that might currently be nil. If the optional have a value then the property, method, or subscript call succeeds and if the optional is nil thenthe property, method, or subscript call returns nil.

You can chain multiple queries together but if any chain in the link is nil, the entire chain will fail.

Optional Chaining as Forced Unwrapping Alternative

Optional chaining is specified by placing a question mark (?) after the optional value where you call a property, method or subscript if optional is not nil.

Optional Chaining Forced Unwrapping
Optional chaining fails when the optional is nil. Forced unwrapping triggers a runtime error when the optional is nil.
The operator ? is placed after the optional value to call property, method or subscript ! is placed after the optional value to call property, method or subscript to force unwrapping of value.

Optional Chaining example (without declaring value in base class)

The result of the optional chaining is the same as the expected return value but wrapped in an optional. It means that a property which generally returns Int will return Int? when accessed through optional chaining.

Let's take an example to see the difference between optional chaining and forced alternative:

Program for Optional Chaining with ? Operator

Output:

Student name cannot be retrieved 

Here, Exam is a class name and contains student as membership function. Subclass is declared as Toppers and name is a membership function which is initialized as "Intelligent". The call to the superclass is initialized by creating an instance "stud" with optional "?".

Since, the value is not declared in the base class so, nil is stored and displayed by else handler block.

Model Class for Optional Chaining & Accessing Properties

It is used when you have to declare more than one subclass as a model class. It facilitates you to define complex model and to access the methods, properties, subscripts, sub properties.

Example

Output:

Rectangle Area is not specified

Next Topic#




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA