0
votes

I want to extend the default behaviour of the CustomStringConvertible protocol in my class, by adding some extra output.

For example, say you have this class in a project called Bar:

class Baz {
   let x = 42
}
let b = Baz()

When doing a po(b), the output will be Bar.Baz

I want to display some extra stuff, such as the value of x, without having to type again Bar.Baz

Is this possible?

1
Please show us an example of what you want to happen when you print a custom class. - Alex Popov
The protocol doesn't have a default implementation, each class/struct must implement it's own version - Cristik
@AlexPopov I just edited the question - cfischer
Good question, but there are still no direct answer. Can it be reopened somehow? - kelin

1 Answers

3
votes

The reason why most of the classes you use have a default implementation of CustomStringConvertible is because NSObject (the superclass of all Obj-C classes) implements it.

If you have defined your own Swift base class, you must first declare that it conform to CustomStringConvertible and then implement it, e.g.

class Dog: CustomStringConvertible {
  // some code and stuff here
  var name = "Bobby"

  // conform to CustomStringConvertible
  var description: String {
    return "\(NSStringFromClass(self.dynamicType)) \(name)"
  }
}

print(Dog()) // outputs: "__lldb_expr_70.Dog Bobby" in Playground

A class that does not conform to CustomStringConvertible merely prints the class name.