Swift program to pass an object as a parameter

Here, we are going to learn how to pass an object as a parameter in Swift programing language?
Submitted by Nidhi, on July 05, 2021

Problem Solution:

Here, we will create a class with user define methods. Then we will pass an object as a parameter to add the values of data members with the current object.

Program/Source Code:

The source code to pass an object as a parameter is given below. The given program is compiled and executed successfully.

// Swift program to pass an object as a parameter

import Swift

class Sample {
    var num:Int

    init(num:Int) {
        self.num = num
    }

    func addObjects(S:Sample)->Int{
        let temp = Sample(num:0)
        temp.num = self.num + S.num
        return temp.num
    }
}

var obj1 = Sample(num:10)
var obj2 = Sample(num:20)

var result = obj1.addObjects(S:obj2)

print("Object1: ",obj1.num)
print("Object2: ",obj2.num)
print("Addition is: ",result)

Output:

Object1:  10
Object2:  20
Addition is:  30

...Program finished with exit code 0
Press ENTER to exit console.

Explanation:

In the above program, we imported a package Swift to use the print() function using the below statement,

import Swift

Here, we created a class Sample with two data member num. The Sample contains init() and addObjects() methods. Then we created the objects of the Sample class and then added objects obj1 and obj2 using the addObjects() method and assign the result to the result variable. After that, we printed the result on the console screen.

Swift Classes & Objects Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.