Swift Classes and Objects with Examples

Job-ready Online Courses: Dive into Knowledge. Learn More!

Classes signify being a part of Object Oriented Programming. It is a blueprint for the creation of objects. It helps in defining the behavior and structure of an object. In this article, we’ll discuss how to define a class and its objects and how to initialize it. We’ll go through related concepts along with relevant examples.

Defining a Swift Class

We define a swift class by writing the class keyword followed by the class name. The syntax for defining a class is as follows.

class ClassName{
    //class statements
}

For example,

class Company{
    var companyName = ""
}

Swift Class Objects

Objects help us create instances of the classes. We can use these objects to use in our code as per our requirements.

Syntax to create an object.

var newObjectName = ClassName()

In the example given below, we create an instance company1 of the class Company.

class Company{
    var companyName = "DataFlair"
    var foundingYear = 2014
}

var company1 = Company()

A single class can have multiple objects. We can create multiple instances of these classes based on our requirements.

Class Properties and Methods in Swift

Every class can have its own properties and methods. We declare variables/constants related to the class as Properties. We define functions belonging to a particular class as Class methods.

We can access these methods and properties using the dot notation ‘.’.

The following example depicts how we can define the properties and methods of a class. It also shows how we can access these.

class Company{
    var companyName = "DataFlair"
    var foundingYear = 2014
    
    func greet(){
        print("Hello from \(companyName)")
    }
}

var company1 = Company()
company1.greet()
print(company1.foundingYear)

Output:

Hello from DataFlair
2014

Swift Class Initializer

In the examples above, we have given initial values to all our class properties. These values are known as the default values of these properties. We can also initialize these values. We do that with the help of an initializer.

The syntax of creating an initializer is as follows.

class ClassName{
var property1: dataType
var property2: dataType

init(property1, property2){
    //assignment statements
}
}

Since we are using an initializer in the class, we need to pass these property values when we create an instance of the class. For example,

class Company{
    var companyName: String
    var foundingYear: Int
    
    init(companyName: String, foundingYear: Int){
        self.companyName = companyName
        self.foundingYear = foundingYear
    }
}

var company1 = Company(companyName: "DataFlair", foundingYear: 2014)
print(company1.companyName, company1.foundingYear)

Output:

DataFlair 2014

Class as Reference Type

Classes are reference types in Swift. This means that when we assign an instance of a class to a variable/constant or we pass it as an argument in a function, we work with its reference to the same object stored in the memory. If we change one of the references, then it affects all the references to that object in the program.

For example,

class ReferenceTypeExample {
    var name: String
    init(name: String) {
        self.name = name
    }
}

let example1 = ReferenceTypeExample(name: "Swift")
// example2 references the same object
let example2 = example1 
print("Original values: \(example1.name), \(example2.name)")

example2.name = "DataFlair"
// both example1 & example2 points to the same object
print("Updated values: \(example1.name), \(example2.name)")

Output:

Original values: Swift, Swift
Updated values: DataFlair, DataFlair

Class Identity Operators in Swift

In Swift, we can create several class instances. Some of these multiple instances might point to the same reference. We can use identity operators to verify these variables or constants pointing to specific instances.

The table below explains how to check for identical and non-identical identifiers.

IdenticalNot Identical
=== Operator!== Operator
A statement is true if the given identifiers are pointing to the same instance.A statement is false if the given identifiers are pointing to the same instance.

Class and Structure in Swift

Classes and Structures are pretty similar in some contexts. However they have some significant differences between them, which makes them useful for separate use cases. We have discussed the differences between a class and structure below.

Differences of Class & Structure

ClassesStructures
Class is a reference type.Structure is a value type.
They support inheritance.They do not support inheritance.
Properties are mutable even when declared as a constant.Properties are immutable if declared as a constant.
They have a separate initialiser to initialize the propertiesThey have a memberwise initialiser to initialize the properties by default

Conclusion

Classes are a blueprint of object-oriented programming. In this article, we have discussed the basics of a class. We have seen how to define a swift class and how to use and access its properties and methods. We have also seen how to use an initializer and identity operators in swift. We also understood the differences between a class and a structure.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *