The source code to create an array of objects is given below. The given program is compiled and executed successfully.
// Swift program to create an array of objects
import Swift
class Sample {
var num1:Int
var num2:Int
init(num1:Int, num2:Int) {
self.num1 = num1
self.num2 = num2
}
func printvalues() {
print("\tNum1: ",num1)
print("\tNum2: ",num2)
}
}
let obj = [Sample(num1:10,num2:20),Sample(num1:100,num2:200)]
print("Object1: ")
obj[0].printvalues()
print("Object2: ")
obj[1].printvalues()
Output:
Object1:
Num1: 10
Num2: 20
Object2:
Num1: 100
Num2: 200
...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. The Sample contains init() and printValues() method. Then we created the array of objects and printed the values of data members on the console screen.
Program/Source Code:
The source code to create an array of objects 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. The Sample contains init() and printValues() method. Then we created the array of objects and printed the values of data members on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer