Swift Classes

Classes in Swift are similar to Structures in Swift. These are building blocks of flexible constructs. You can define class properties and methods like constants, variables and functions are defined. In Swift 4, you don't need to create interfaces or implementation files while declaring classes. Swift 4 facilitates you to create classes as a single file and the external interfaces will be created by default when the class is initialized.

Benefits of Swift Classes

  • By using classes, you can apply inheritance to acquire properties of one class to another class.
  • Type casting enables the user to check class type at run time.
  • Deinitializers take care of releasing memory resources.
  • Reference counting allows the class instance to have more than one reference.

Characteristics of Classes and Structures in Swift

  • In classes, properties are defined to store values.
  • Subscripts are defined for providing access to values.
  • Methods are initialized to improve functionality.
  • Initial states are defined by initializers.
  • Functionalities are expanded beyond default values.

Syntax

Example

In the following program there are two classes Salary and EmpSalary.

Output:

After running the above program, you will see the following output:

Employee salary is 10000

Note: In the above example, class properties are accessed by the '.' syntax. Property name is separated by a '.' after the instance name.

Class Identity Operators

Swift4 classes refer multiple constants and variables pointing to a single instance. To know about the constants and variables pointing to a particular class, instance identity operators are used. Class instances are always passed by reference. In Classes, NSString, NSArray, and NSDictionary instances are always assigned and passed around as a reference to an existing instance, rather than as a copy.

Identical to Operators

  • Operator used is (===).
  • Returns true when two constants or variables pointing to a same instance.

Not Identical to Operators

  • Operator used is (!==).
  • Returns true when two constants or variables pointing to a different instance.





Latest Courses