Javatpoint Logo
Javatpoint Logo

Swift4 Typecasting

Typecasting is used in Swift4 to validate the type of an instance. It is used to check whether the instance type belongs to a particular super class or subclass or it is defined in its own hierarchy.

Swift 4 type casting provides two operators:

  • 'is': This operator is used to check the type of a value.
  • 'as': This operator is used to cast the type value to a different type.

To Define a Class Hierarchy

Type casting is also used to check whether the instance type follows particular protocol conformance standard or not. It also checks hierarchy of classes, its subclasses and its instances to make it as a same hierarchy.

Example:

Output:

Instance physics is: Mechanics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz

How to do Type Checking

The "is" operator is used to do type checking. It checks whether the instance belongs to particular subclass type and returns 'true' if it belongs otherwise returns 'false'.






Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA