Swift program to create a class with the user-defined methods

Here, we are going to learn how to create a class with the user-defined methods in Swift programming language?
Submitted by Nidhi, on July 05, 2021

Problem Solution:

Here, we will create a user-defined class with a user-defined method to set and get the value of data members.

Program/Source Code:

The source code to create a class with a user-defined method is given below. The given program is compiled and executed successfully.

// Swift program to create a class with 
// the user-defined methods

import Swift

class Sample {
    var num1:Int
    var num2:Int

    init(num1:Int, num2:Int) {
        self.num1 = num1
        self.num2 = num2
    }

    func setvalues(num1:Int, num2:Int) {
        self.num1 = num1
        self.num2 = num2
    }

    func printvalues() {
        print("Num1: ",num1)
        print("Num2: ",num2)
    }
}

let obj1 = Sample(num1:100,num2:200)

print("Object1: ")
obj1.printvalues()

let obj2 = Sample(num1:0,num2:0)
obj2.setvalues(num1:1000,num2:2000)

print("Object2: ")
obj2.printvalues()

Output:

Object1: 
Num1:  100
Num2:  200
Object2: 
Num1:  1000
Num2:  2000

...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 members num1 and num2. We also defined the init() method with two methods to set and get values of data members. Then we created the two objects and set and get values of data members and printed the result on the console screen.

Swift Classes & Objects Programs »






Comments and Discussions!

Load comments ↻






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