Junior — Middle
What does implementing the CustomStringConvertible protocol in Swift mean and what is it used for?
sobes.tech AI
Answer from AI
In Swift, the CustomStringConvertible protocol is used to provide a custom textual representation of an object. If a type adopts this protocol, it must define the description property, which returns a string — a description of the object.
This is useful when you want an informative and understandable string to be displayed when printing the object with print() or concatenating it with other strings, rather than the default type description.
Example:
struct User: CustomStringConvertible {
var name: String
var age: Int
var description: String {
return "User(name: \(name), age: \(age))"
}
}
let user = User(name: "Ivan", age: 30)
print(user) // Outputs: User(name: Ivan, age: 30)
Thus, implementing CustomStringConvertible improves code readability and debugging by controlling how objects are displayed as strings.