Swift program to demonstrate the 'self' keyword within the class

Here, we are going to demonstrate the 'self' keyword within the class in Swift programming language.
Submitted by Nidhi, on July 05, 2021

Problem Solution:

Here, we will create a user-defined class and demonstrate the self keyword. The self keyword is used to differentiate the same data members and local variables.

Program/Source Code:

The source code to demonstrate the self keyword within the class is given below. The given program is compiled and executed successfully.

// Swift program to demonstrate the "self" keyword 
// within the class

import Swift

class Sample {
    var num1:Int
    var num2:Int

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

let obj = Sample(num1:10,num2:20)

print("Num1: ",obj.num1)
print("Num2: ",obj.num2)

Output:

Num1:  10
Num2:  20

...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 inside the Sample class. The init() method is used to initialize data members. In the init() method, we used data members and local variables with the same name. To resolve this problem, we used the self keyword. Then we created the object of the Sample class and initialized the data members. After that, we printed the value of data members on the console screen.

Swift Classes & Objects Programs »





Comments and Discussions!

Load comments ↻





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