How do I implement custom StringConvertible and CustomDebugStringConvertible in Swift?

In Swift, you can create types that provide custom string representations by conforming to the CustomStringConvertible and CustomDebugStringConvertible protocols. This allows you to control how instances of your types are represented as strings in print statements and during debugging.

Here’s a simple example of a class implementing these protocols:

struct Person: CustomStringConvertible, CustomDebugStringConvertible { var name: String var age: Int var description: String { return "Person(name: \(name), age: \(age))" } var debugDescription: String { return "Debug: Person { name: \(name), age: \(age) }" } } let person = Person(name: "Alice", age: 30) print(person) // Output: Person(name: Alice, age: 30) print(person.debugDescription) // Output: Debug: Person { name: Alice, age: 30 }

Swift StringConvertible CustomDebugStringConvertible Swift Programming CustomString Debugging in Swift