Skip to content

Instantly share code, notes, and snippets.

@norio-nomura
Last active April 26, 2016 12:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save norio-nomura/e1e0cff0fc7c3c80f65d5af7c56450e1 to your computer and use it in GitHub Desktop.
Save norio-nomura/e1e0cff0fc7c3c80f65d5af7c56450e1 to your computer and use it in GitHub Desktop.
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