Adding methods with extensions

Sometimes, we would like to add methods to an existing class. We already know how to do this; we just need to go to its Swift source file and add a new method within the class body. However, sometimes, we cannot access the source code for the class, or it isn't convenient to make changes to it. A typical example of this situation is a class, struct, or any other type that is part of the standard language elements. For example, we might want to add a method that we can call in any Int value to initialize either a 2D or 3D point with all its elements set to the Int value.

The following lines declare a simple Point2D class that represents a mutable 2D point with the x and y elements. The class conforms to the CustomStringConvertible ...

Get Swift 3 ObjectOriented Programming - Second Edition 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.