ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.