Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

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?

like image 978
Nao Ohta Avatar asked Jun 02 '16 02:06

Nao Ohta


2 Answers

try this if you want :

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

UPDATE:

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 :-)

like image 63
Wilson XJ Avatar answered Nov 15 '22 21:11

Wilson XJ


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.
like image 22
Mike C. Avatar answered Nov 15 '22 23:11

Mike C.