Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import Foundation
/// A reference type that provides a better default representation than the class name
public protocol DefaultReflectable: Streamable {}
/// A default implementation that enables class members to display their values
extension DefaultReflectable {
/// Constructs a better representation using reflection
internal func DefaultDescription<T>(instance: T) -> String {
let mirror = Mirror(reflecting: instance)
let chunks = mirror.children.map({
(label: String?, value: Any) -> String in
if let label = label {
if value is String {
return "\(label): \"\(value)\""
}
return "\(label): \(value)"
} else {
return "\(value)"
}
})
if chunks.isEmpty {
return "\(instance)"
} else {
let chunksString = chunks.joinWithSeparator(", ")
return "\(mirror.subjectType)(\(chunksString))"
}
}
public func writeTo<Target : OutputStreamType>(inout target: Target) {
target.write(DefaultDescription(self))
}
}
struct S1 {var a = 1; var b = "x"}
class C1 {var a = 1; var b = "x"}
class C2: DefaultReflectable {var a = 1; var b = "x"}
class C3: NSObject {var a = 1; var b = "x"}
class C4: NSObject, DefaultReflectable {var a = 1; var b = "x"}
print(S1()) // S1(a: 1, b: "x")
print(C1()) // C1
print(C2()) // C2(a: 1, b: "x")
print(C3()) // <__lldb_expr_163.C3: 0x7fb52452dc00>
print(C4()) // C4(a: 1, b: "x")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment