Skip to content

Instantly share code, notes, and snippets.

@tartakovsky
Last active December 1, 2015 15:01
Show Gist options
  • Save tartakovsky/03260cbd5f1f6561ba8f to your computer and use it in GitHub Desktop.
Save tartakovsky/03260cbd5f1f6561ba8f to your computer and use it in GitHub Desktop.
Default description property getter for types that conform to CustomStringConvertible
How to use it:
1. Add the file to the project
2. Append CustomStringConvertible or CustomDebugStringConvertible protocol to the type you want to have description
3. Now you can call object.description on any custom Class or Struct you've made
import Foundation
extension CustomStringConvertible {
var description: String {
let mirror = Mirror(reflecting: self)
var output = ""
output.appendContentsOf("\(mirror.subjectType) (\n")
for case let (label?, value) in mirror.children {
output.appendContentsOf(" \(label) = \(value)\n")
}
output.appendContentsOf(")\n")
return output
}
}
extension CustomDebugStringConvertible {
var debugDescription: String {
let mirror = Mirror(reflecting: self)
var output = ""
output.appendContentsOf("\(mirror.subjectType) (\n")
for case let (label?, value) in mirror.children {
output.appendContentsOf(" \(label) = \(value)\n")
}
output.appendContentsOf(")\n")
return output
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment