ADVERTISEMENT
ADVERTISEMENT

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 »


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.