是否有任何dump()函数返回一个字符串?

时间:2016-06-02 02:49:13

标签: ios swift

我喜欢Swift的dump()函数,

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!
 */

但dump()不返回字符串。它只是打印到控制台,并返回第一个参数。

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

是否有任何dump()函数返回一个字符串?

2 个答案:

答案 0 :(得分:10)

来自: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.

示例:

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

答案 1 :(得分:1)

如果你想要试试这个:

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

UPDATE:

你可以组合你喜欢的字符串使用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)

希望它有所帮助: - )