Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
This chapter is from the book

Making Types Printable

If you use a Vector value in string interpolation, you will not get a very pleasing result:

println("Gravity is \(gravity).")             "Gravity is __lldb_expr_247.Vector."

You can improve this by conforming to the Printable protocol, which looks like this:

protocol Printable {
    var description: String { get }
}

We will cover protocols in more detail in Chapter 6, but the short version is that a protocol defines a set of properties or methods. In order to conform to a protocol, your type must implement the required properties and methods.

To conform to Printable, you must implement a read-only computed property called description to return a String. Start by declaring that Vector conforms to Printable:

struct Vector {
struct Vector: Printable {
    var x: Double
    var y: Double

Finally, implement description:

struct Vector: Printable {
    ...

    var description: String {
        return "(\(x), \(y))"
    }
}

Your Vector s now look great in strings:

println("Gravity is \(gravity).")             "Gravity is (0.0, -9.8)."
  • + Share This
  • 🔖 Save To Your Account