Swift program to create a class with the init() method

Here, we are going to learn how to create a class with the init() method in Swift programming language?
Submitted by Nidhi, on July 05, 2021

Problem Solution:

Here, we will create a user-defined class with the init() method. The init() method is used to initialize data members of the created class.

Program/Source Code:

The source code to create a class with the init() method is given below. The given program is compiled and executed successfully.

// Swift program to create a class 
// with the "init" method

import Swift

class Sample {
    var num1:Int
    var num2:Int
    
    init(n1:Int, n2:Int) {
        num1 = n1
        num2 = n2
    }
}

let obj = Sample(n1:10,n2: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. 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.