{

How to print an array of objects in swift with example


 print an array of objects  in the swift with example

Multiple ways to print an array of objects in swift code examples

  • Iterate array using for loop and print an object, each object overrides description method
  • dump method

Sometimes, We have an array of objects and want to print the object values for debugging purposes.

For example, Let’s declare an object of a Student class

import Foundation
class Student {
    var marks: Int =  0
    var id: Int;
    init ( _ id: Int, _ marks: Int){
        self.marks = marks
        self.id=id
    }

}

Create an array of students with default values.

let students = [Student(11,40),Student(21,99),Student(10,89)]
print(students)

Displays the objects using print functions shown below

[main.Student, main.Student, main.Student]

It is not useful for debugging to know what value objects contain at runtime.

There are multiple ways to print an array of objects.

Swift array of objects print values

  • using for loop

One of the ways, to print an object is by using for loop

Iterate each object using for loop and print the object.

import Foundation
class Student :CustomStringConvertible{
    var marks: Int =  0
    var id: Int;
    init ( _ id: Int, _ marks: Int){
        self.marks = marks
        self.id=id
    }
 var description : String {
                return "id :\(id)  marks \(marks)"

    }
}

let students = [Student(11,40),Student(21,99),Student(10,89)]
for the student in students {
  print(student)
}

Output:

id :11  marks 40
id :21  marks 99
id :10  marks 89

To print object properties, implement CustomStringConvertible and provide implements description property as described in print object in swift

or you can use print directly an array using print

print(students)

Output:

[id :11  marks 40, id :21  marks 99, id :10  marks 89]
  • dump method

you can use the dump method directly as given below

dump(students)
3 elements
  ▿ id :11  marks 40 #0
    - marks: 40
    - id: 11
  ▿ id :21  marks 99 #1
    - marks: 99
    - id: 21
  ▿ id :10  marks 89 #2
    - marks: 89
    - id: 10
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.