Reference: StackOverflow – Print Struct name in swift
Here’s the code for printing the properties of an object
func printProperties(_ object: Any) {
var properties = [String: Any]()
Mirror(reflecting: object).children.forEach { (child) in
if let property = child.label {
properties[property] = child.value
}
}
print(object)
print(type(of: object))
print(properties)
}
How the output would look like when used on a struct
struct PersonStruct {
public let firstName: String
internal let lastName: String // default access level is internal
private let email: String = "test@example.com"
}
let person = PersonStruct(firstName: "John", lastName: "Doe")
printProperties(person)
/* Output
PersonStruct(firstName: "John", lastName: "Doe", email: "test@example.com")
PersonStruct
["lastName": "Doe", "email": "test@example.com", "firstName": "John"]
*/
How the output would look like when used on a class
class PersonClass {
public let firstName: String
internal let lastName: String // default access level is internal
private let email: String = "test@example.com"
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
let person = PersonClass(firstName: "John", lastName: "Doe")
printProperties(person)
/* Output
MyApp.PersonClass
PersonClass
["lastName": "Doe", "email": "test@example.com", "firstName": "John"]
*/

