Swift program to create an array of the structure

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

Problem Solution:

Here, we will create a structure Student. Then we will create an array of structure and set student information using the append() function. After that, we will print student information on the console screen.

Program/Source Code:

The source code to create an array of the structure is given below. The given program is compiled and executed successfully.

// Swift program to create an array of the structure

import Swift

struct Student {
    var id: Int
    var name:String
    var fees:Int

    init(id:Int, name:String, fees:Int) {
        self.id=id
        self.name=name
        self.fees=fees
    }
}

var stuArr: [Student] = []

stuArr.append(Student(id:1001,name:"Rahul",fees:8000))
stuArr.append(Student(id:1002,name:"Rohit",fees:5000))
stuArr.append(Student(id:1003,name:"Virat",fees:7000))

print(stuArr[0])
print(stuArr[1])
print(stuArr[2])

Output:

Student(id: 1001, name: "Rahul", fees: 8000)
Student(id: 1002, name: "Rohit", fees: 5000)
Student(id: 1003, name: "Virat", fees: 7000)

...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 structure Student with three fields id, name, and fees, and also defined init() function to initialize Student structure. Then we created the array of Student structure and set student information using the append() function. After that, we printed student information on the console screen.

Swift Structures Programs »





Comments and Discussions!

Load comments ↻





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