-
-
Save BryanJBryce/cfca2d455f3c6a9c11d9 to your computer and use it in GitHub Desktop.
A default protocol implementation for CustomDebugStringConvertible that uses Mirror for introspection. This is meant for debugging only.
This file contains hidden or 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
public extension CustomDebugStringConvertible { | |
var debugDescription: String { | |
return debugDescription() | |
} | |
func debugDescription(indentationLevel: Int = 0) -> String { | |
let indentString = (0..<indentationLevel).reduce("") { tabs, _ in tabs + "\t" } | |
var s = "\(self.dynamicType)" | |
let mirror = Mirror(reflecting: self) | |
let children = mirror.children | |
if children.count == 0 { | |
return "\(s) = \(debugDescription)," | |
} | |
s += " {" | |
s = children.reduce(s) { | |
reducedString, child in | |
if let aChild = child.1 as? CustomDebugStringConvertible { | |
let childDescription = aChild.debugDescription(indentationLevel + 1) | |
return reducedString + "\n\(indentString)\t\(child.0!): \(childDescription)" | |
} else { | |
return reducedString + "\n\(indentString)\t\(child.0!): \(child.1)," | |
} | |
} | |
s = s.substringToIndex(s.characters.endIndex.predecessor()) | |
s += "\n\(indentString)}" | |
return s | |
} | |
} | |
// Sample usage | |
/* | |
struct Person: CustomDebugStringConvertible { | |
let name: String | |
let address: Address | |
let children: [Person]? | |
} | |
struct Address: CustomDebugStringConvertible { | |
let city: String | |
let state: String | |
let zip: String | |
let streetNumber: String | |
let streetName: String | |
let suiteNumber: String? | |
let randomNumber: Int | |
init(city: String, state: String, zip: String, streetNumber: String, streetName: String, suiteNumber: String? = nil) { | |
self.city = city | |
self.state = state | |
self.zip = zip | |
self.streetNumber = streetNumber | |
self.streetName = streetName | |
self.suiteNumber = suiteNumber | |
self.randomNumber = Int(arc4random_uniform(1000)) | |
} | |
} | |
let address = Address(city: "Lehi", state: "UT", zip: "84043", streetNumber: "123", streetName: "Fake st") | |
//print(address) | |
let child = Person(name: "joe", address: address, children: nil) | |
let person = Person(name: "matt", address: address, children: [child]) | |
print(person) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment