Last active
November 14, 2017 07:33
-
-
Save khawajafarooq/e2457ff6fec560a9261b7c7ebfa88408 to your computer and use it in GitHub Desktop.
Customize the console printing of object types in swift
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 UIKit | |
// The protocol use to convert your instance into textual pretty form | |
protocol CustomPrintable: CustomStringConvertible { | |
var emoji: String { get } | |
} | |
// Defaults | |
extension CustomPrintable { | |
var emoji: String { | |
return "📝" | |
} | |
var description: String { | |
var desc: String = "\(type(of: self)) \(emoji)\n" | |
let object = Mirror(reflecting: self) | |
for property in object.children { | |
guard let propertyName = property.label else { | |
continue | |
} | |
desc += "\(propertyName): \(property.value)\n" | |
} | |
return desc | |
} | |
} | |
// Custom Printable value type struct | |
struct User { | |
let firstName: String | |
let lastName: String | |
let age: Int | |
} | |
// Protocol conformance (optional) | |
extension User: CustomPrintable { | |
var emoji: String { | |
return "👤" | |
} | |
} | |
let user = User(firstName: "John", lastName: "Doe", age: 22) | |
print(user) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment