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.
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.
Output:
Explanation:
In the above program, we imported a package Swift to use the print() function using the below statement,
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.
need an explanation for this answer? contact us directly to get an explanation for this answer