Making Types Printable

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

p​r​i​n​t​l​n​(​"​G​r​a​v​i​t​y​ ​i​s​ ​\​(​g​r​a​v​i​t​y​)​.​"​)​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​"​G​r​a​v​i​t​y​ ​i​s​ ​_​_​l​l​d​b​_​e​x​p​r​_​2​4​7​.​V​e​c​t​o​r​.​"​

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

p​r​o​t​o​c​o​l​ ​P​r​i​n​t​a​b​l​e​ ​{​
 ​ ​ ​ ​v​a​r​ ​d​e​s​c​r​i​p​t​i​o​n​:​ ​S​t​r​i​n​g​ ​{​ ​g​e​t​ ​}​
}​

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 ...

Get Cocoa Programming for OS X: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.