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

I like the Swift dump () function like this one

class MyClass { let a = "Hello" let b = "Bye!" init() {} } let myClass = MyClass() dump(myClass) // Printed out these lines to Xcode console /* ▿ MyClass #0 - a: Hello - b: Bye! */ 

But dump () does not return a string. It simply prints to the console and returns the first parameter.

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

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

+5
source share
2 answers

From: https://github.com/apple/swift/blob/master/stdlib/public/core/OutputStream.swift

 /// You can send the output of the standard library `print(_:to:)` and /// `dump(_:to:)` functions to an instance of a type that conforms to the /// `TextOutputStream` protocol instead of to standard output. Swift's /// `String` type conforms to `TextOutputStream` already, so you can capture /// the output from `print(_:to:)` and `dump(_:to:)` in a string instead of /// logging it to standard output. 

Example:

 let myClass = MyClass() var myClassDumped = String() dump(myClass, to: &myClassDumped) // myClassDumped now contains the desired content. Nothing is printed to STDOUT. 
+5
source

try this if you want:

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

UPDATE:

you can combine the string you like using 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" } print(string) 

hope this will be useful :-)

+1
source

All Articles