What is the Swift equivalent of Java toString()
to print the state of a class instance?
A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.
toString is automatically called for the frog1 Object constructed by the default constructor.
By default the toString() method will return a string that lists the name of the class followed by an @ sign and then a hexadecimal representation of the memory location the instantiated object has been assigned to.
This is a useful addition to this page, however the C++ implementation is significantly different to the one in Java/C#. In those languages, ToString () is a virtual function defined on the base class of all objects, and is therefore used as a standard way to express a string representation of any object.
In those languages, ToString () is a virtual function defined on the base class of all objects, and is therefore used as a standard way to express a string representation of any object. These functions on std::string only apply to built-in types. The idiomatic way in C++ is to override the << operator for custom types.
In Java you could override the toString () method for similar purpose. Show activity on this post. In case your operator<< wants to print out internals of class A and really needs access to its private and protected members you could also declare it as a friend function:
The description
property is what you are looking for. This is the property that is accessed when you print a variable containing an object.
You can add description
to your own classes by adopting the protocol CustomStringConvertible
and then implementing the description
property.
class MyClass: CustomStringConvertible { var val = 17 public var description: String { return "MyClass: \(val)" } } let myobj = MyClass() myobj.val = 12 print(myobj) // "MyClass: 12"
description
is also used when you call the String
constructor:
let str = String(myobj) // str == "MyClass: 12"
This is the recommended method for accessing the instance description (as opposed to myobj.description
which will not work if a class doesn't implement CustomStringConvertible
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With