Last active
December 1, 2015 15:01
-
-
Save tartakovsky/03260cbd5f1f6561ba8f to your computer and use it in GitHub Desktop.
Default description property getter for types that conform to CustomStringConvertible
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
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 |
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 | |
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