Swift program to create an array of objects

Here, we are going to learn how to create an array of objects in Swift programming language?
Submitted by Nidhi, on July 05, 2021

Problem Solution:

Here, we will create a class with user define methods. Then we will create an array of objects and print the values of data members.

Program/Source Code:

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.

Swift Classes & Objects Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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