Swift Classes

In Swift, a class is a flexible construct that allows you to define custom data types with properties and methods. Classes are a reference type, meaning that when you assign an instance of a class to a variable or a constant, you are actually setting a reference to that instance. In this tutorial, we will discuss Swift classes, their properties, and methods with examples.

Benefits of having Classes:

  • Classes are reference types, which means that when a class instance is assigned to a variable, that variable will reference the same instance of the class in memory.
  • Classes can inherit from other classes, which allows for code reuse and better organization of code.
  • Classes can have deinitializers, which are methods that are called when an instance of the class is deallocated from memory.
  • Classes can have optional property types, which allows properties to be nil until they are initialized.

Common Characteristics of Classes and structures:

  • Both classes and structures can have properties, methods, and initializers.
  • Both classes and structures can conform to protocols and implement protocol requirements.
  • Both classes and structures can be extended to add additional functionality.
  • Both classes and structures can be used to create instances and store data.

Creating a Swift Class

In Swift, you create a class with the class keyword followed by the name of the class. Here is an example:

1class Person { 2 var name: String 3 var age: Int 4 5 init(name: String, age: Int) { 6 self.name = name 7 self.age = age 8 } 9 10 func display() { 11 print("Name: \(name), Age: \(age)") 12 } 13}

In the above example, we have defined a Person class with two properties: name and age. The init method is used to initialize the class properties with the values passed as arguments. The display method is used to display the name and age properties of the Person object.

Creating an Instance of a Class

To create an instance of a class, you use the class name followed by parentheses. Here is an example:

1let person = Person(name: "William Max", age: 22)

In the above example, we have created an instance of the Person class and assigned it to the person constant. We have passed the name and age values to the init method to initialize the properties of the Person object.

Accessing Properties and Methods

To access the properties and methods of a class, you use the dot notation. Here is an example:

1print(person.name) // William Max 2print(person.age) // 22 3person.display() // Name: William Max, Age: 22

In the above example, we have accessed the name and age properties of the person object and called the display method.