Blog / March 26, 2023 / 4 mins read / By Mahi Garg

Classes in Swift

In the world of Swift, classes form the cornerstone of object-oriented programming (OOP). They provide a powerful mechanism to create blueprints for objects, allowing you to encapsulate data and behaviors together in a structured manner. In this blog, we’ll dive into the world of classes in Swift, explore their features, benefits, and demonstrate how they can be used to build sophisticated and reusable code with practical examples.

What are Classes?

In Swift, a class is a reference type that defines a blueprint for creating objects. Unlike structs, which are value types, classes are passed around by reference, meaning multiple variables can point to the same underlying instance. Classes support inheritance, enabling you to create hierarchies of related objects, and they play a pivotal role in achieving abstraction and polymorphism, two essential principles of OOP.

Declaring Classes

Let’s start by creating a simple class to represent a Person:

class Person {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    func sayHello() {
        print("Hello, my name is \(name) and I am \(age) years old.")
    }
}

In this example, we’ve defined a class called Person with two properties: name and age, along with an initializer to set their initial values. The class also contains a method sayHello() to introduce the person.

Creating Instances of a Class

Now that we have our Person class, let’s create instances of it:

let john = Person(name: "John", age: 30)
let jane = Person(name: "Jane", age: 25)

Accessing Properties and Calling Methods

We can access the properties and call methods of the instances using dot notation:

print(john.name) // Output: John
print(jane.age)  // Output: 25

john.sayHello() // Output: Hello, my name is John and I am 30 years old.
jane.sayHello() // Output: Hello, my name is Jane and I am 25 years old.

Class Inheritance

One of the key features of classes is inheritance, which allows you to create a new class based on an existing one, inheriting its properties and methods. Let’s create a subclass Student that inherits from the Person class and adds an additional property:

class Student: Person {
    var school: String

    init(name: String, age: Int, school: String) {
        self.school = school
        super.init(name: name, age: age)
    }

    override func sayHello() {
        print("Hello, my name is \(name), I am \(age) years old, and I study at \(school).")
    }
}

Creating Instances of a Subclass

let alice = Student(name: "Alice", age: 22, school: "ABC University")
alice.sayHello() // Output: Hello, my name is Alice, I am 22 years old, and I study at ABC University.

Access Control

Swift provides access control to restrict the visibility of properties, methods, and other components of a class. There are three access levels: public, internal, and private. The default access level is internal, which means the components are accessible within the same module. Let’s add access control to our Person class:

class Person {
    private var name: String
    internal var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    internal func sayHello() {
        print("Hello, my name is \(name) and I am \(age) years old.")
    }
}

Conclusion

Classes are a powerful tool in Swift for building complex, hierarchical, and reusable code structures. They allow you to create blueprints for objects, promote code organization through inheritance and encapsulation, and enable the use of essential OOP principles such as abstraction and polymorphism.

In this blog, we’ve covered the basics of classes in Swift and demonstrated how to create, use, and benefit from them in your Swift projects. Whether you’re working on iOS apps, macOS applications, or any other Swift-based project, classes will undoubtedly play a significant role in designing efficient and maintainable solutions.

By understanding the nuances of classes and incorporating them into your Swift code, you can create robust, flexible, and scalable applications. So, the next time you find yourself building a complex data model, creating an inheritance hierarchy, or leveraging OOP principles, consider Swift classes as your go-to choice for building powerful and expressive solutions! Happy coding! 🚀

Comments