Swift Program to Print object of a class



In this article, we will learn how to write a swift program to print object of a class.

A class object is known as an instance of a class. For example, colour is a class then obj1, obj2, obj3 and obj4 are the objects from the class. A class can have multiple objects.

Syntax

var objectname = Classname()

Here, using the above syntax we can create an object of a class.

Algorithm

Step 1 ? Create a class with properties and a constructor.

Step 2 ? Create a function to print the object of the given class.

Step 3 ? Create an object or the class and assign value to it.

Step 4 ? Call the function(created in step 2) and pass the object into it.

Step 5 ? Print the output.

Example

Following Swift program to print object of a class.

Open Compiler
import Foundation import Glibc // Creating a class class Writer { var name: String var articleCount: Int var language: String // Constructor init(name: String, articleCount: Int, language: String) { self.name = name self.articleCount = articleCount self.language = language } } // Function to print object in more readable form func printObject(objClass: Writer) { print("Name: \(objClass.name)") print("Article Count: \(objClass.articleCount)") print("Programming Language: \(objClass.language)") } // Creating object let objClass = Writer(name: "Mohina", articleCount: 70, language: "C#") printObject(objClass: objClass)

Output

Name: Mohina
Article Count: 70
Programming Language: C#

Here in the above code, we create an object of writer class with the name = Mohina, articleCount = 70 and language = C# and then call printObject() method to print the object's properties.

Example

Following Swift program to print object of a class.

Open Compiler
import Foundation import Glibc // Creating a class class Food { var name: String var Count: Int var Sale: Int // Constructor init(name: String, Count: Int, Sale: Int) { self.name = name self.Count = Count self.Sale = Sale } // Property to print object in more readable form var printObject: String { return "Name: \(name), Per Day Count: \(Count), Sale: \(Sale)%" } } // Creating object let object = Food(name: "Pizza", Count: 100, Sale: 90) print(object.printObject)

Output

Name: Pizza, Per Day Count: 100, Sale: 90%

Here in the above code, we create an object of the Food class with the name = Pizza, Count = 100 and Sale = C#. Now we call the printObject property of the Food class to display the object.

Conclusion

So this is how we can print the object of a class either using function or property.

Updated on: 2023-01-27T12:33:02+05:30

488 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements