naohta naohta - 4 years ago 118
iOS Question

Is there any dump() like function returns a string?

I like Swift's dump() function like this,

class MyClass {
let a = "Hello"
let b = "Bye!"
init() {}
let myClass = MyClass()

dump(myClass) // Printed out these lines to Xcode's console
▿ MyClass #0
- a: Hello
- b: Bye!

But dump() doesn't return a string. It just prints out to the console, and returns 1st parameter itself.

public func dump<T>(x: T, name: String? = default, indent: Int = default, maxDepth: Int = default, maxItems: Int = default) -> T

Is there any dump() like function returns a string?

Answer Source

try this if you want :

let myClass = MyClass()
print("----> \(String(MyClass))")
print("----> \(String(dump(myClass))) ")


you can combine the string you like use Mirror:

let myClass = MyClass()
let mirror = Mirror(reflecting: myClass)
var string = String(myClass) + "\n"
for case let (label?, value) in mirror.children {
        string += " - \(label): \(value)\n"

hope it be helpful :-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download