Q:

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

belongs to collection: Swift Classes & Objects Programs

0

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

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 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.

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

total answers (1)

Swift program to create an array of objects... >>
<< Swift program to demonstrate the \'self\'...