Swift program to overload init() method

Here, we are going to learn how to overload init() method in Swift programming language?
Submitted by Nidhi, on July 13, 2021

Problem Solution:

Here, we will overload the init() method of a class based on the number of arguments to initialize the data member of a class.

Program/Source Code:

The source code to overload the init() method is given below. The given program is compiled and executed successfully.

// Swift program to overload init() method

import Swift

class Sample {
    var val1:Int
    var val2:Int

    init()
    {
        val1 = 10
        val2 = 20
    }

    init(val1:Int, val2:Int)
    {
        self.val1 = val1
        self.val2 = val2
    }
}

var sam1 = Sample()
var sam2 = Sample(val1:30,val2:40)

print("Sam1:")
print("\tVal1: ",sam1.val1)
print("\tVal2: ",sam1.val2)

print("Sam2:")
print("\tVal1: ",sam2.val1)
print("\tVal2: ",sam2.val2)

Output:

Sam1:
        Val1:  10
        Val2:  20
Sam2:
        Val1:  30
        Val2:  40

...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 that contains two data members val1, val2. And, we implemented two init() methods with a different number of arguments. Then we created two objects sam1 and sam2 and initialized the data members. After that, we printed the value of data members of both objects on the console screen.

Swift Subscripts Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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