Q:

Swift program to pass an object as a parameter

belongs to collection: Swift Classes & Objects Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Swift program to return an object from a method... >>
<< Swift program to create an array of objects...