Last active
April 26, 2016 12:46
-
-
Save norio-nomura/e1e0cff0fc7c3c80f65d5af7c56450e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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