Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift equivalent of Java toString()

What is the Swift equivalent of Java toString() to print the state of a class instance?

like image 747
Marcus Leon Avatar asked Apr 13 '16 01:04

Marcus Leon


People also ask

What is toString () in Java?

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.

Is toString automatically called Java?

toString is automatically called for the frog1 Object constructed by the default constructor.

What is the default toString method in Java?

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.

What is the difference between tostring () and tostring () in Java and C++?

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.

What is the use of toString () function in 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. These functions on std::string only apply to built-in types. The idiomatic way in C++ is to override the << operator for custom types.

Is it possible to override the toString () method in Java?

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:


1 Answers

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)

like image 171
vacawama Avatar answered Oct 16 '22 01:10

vacawama