Swift program to return an object from a method

Here, we are going to learn how to return an object from a method in Swift programming 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 and return the object of the class from the method.

Program/Source Code:

The source code to return an object from a method is given below. The given program is compiled and executed successfully.

// Swift program to return an object from a method

import Swift

class Sample {
    var num:Int

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

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

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

var obj3 = obj1.addObjects(S:obj2)

print("Object1: ",obj1.num)
print("Object2: ",obj2.num)
print("Object3: ",obj3.num)

Output:

Object1:  10
Object2:  20
Object3:  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() method. 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 object3 object. 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.