Swift equivalent of Java toString()

Marcus Leon picture Marcus Leon · Apr 13, 2016 · Viewed 37.1k times · Source

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

Answer

vacawama picture vacawama · Apr 13, 2016

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)