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.
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.
there are multiple ways we can print object properties to the console for debugging
let employee=Employee(1,"john",4000)
dump(employee)
Output:
- id: 1
- name: "john"
- salary: 4000
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
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts