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?
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"
}
print(string)
hope it be helpful :-)
From: https://github.com/apple/swift/blob/master/stdlib/public/core/OutputStream.swift
/// You can send the output of the standard library's `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.
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