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
protocol; therefore, it declares a description computed property that returns a string representation for the 2D point. The code file for the sample is included in the swift_3_oop_chapter_08_01
folder.
open class Point2D: CustomStringConvertible...