prints Class object description with example| Java equivalent toString method

In Java, We have a toString method, prints the hashcode with classname by default, You can customize this method to print object properties and values.

In Swift, The same is not available

Let’s declare a class

import Foundation
class Employee   {
    var id: Int;
    var name: String;
    var salary: Int =  0

    init ( _ id: Int, _ name:String, _ salary: Int){
        self.id=id
        self.name = name
        self.salary = salary

    }

}

Next, Create an object and print it

let employee=Employee(1,"john",4000)
print(employee)

It outputs:

main.Employee

How to display the object properties when you print the object variable.

Swift introduced a description property equivalent toString method in java.

Swift object print method properties

there are multiple ways we can print object properties to the console for debugging

  • using the dump method dump method prints object properties in the hierarchy view
let employee=Employee(1,"john",4000)
dump(employee)

Output:

- id: 1
- name: "john"
- salary: 4000
  • using CustomStringConvertible with description property the description property is called during an object is printed to the console using the print method.

The following things need to be added to print the object properties Let’s implement the protocol CustomStringConvertible class to a custom class and provide an implementation for the description property

import Foundation
class Employee : CustomStringConvertible {
var id: Int;
var name: String;
var salary: Int = 0

    init ( _ id: Int, _ name:String, _ salary: Int){
        self.id=id
        self.name = name
        self.salary = salary

    }

var description : String {
return "id :\(id) name \(name) salary \(salary)"
}
}

let employee=Employee(1,"john",4000)
print(employee)

Output:

id :1 name john salary 4000