Generalizing existing classes with generics
In Chapter 3, Encapsulation of Data with Properties, we created a class to represent a mutable 3D vector named MutableVector3D
and a class to represent an immutable version of a 3D vector named ImmutableVector3D
.
Both the versions were capable of working with 3D vectors with Float
values for x
, y
, and z
. We now realize that we also have to work with 3D vectors with Double
values for x
, y
, and z
in both classes. We definitely don't want to create two new classes, such as MutableDoubleVector3D
and ImmutableDoubleVector3D
. We can take advantage of generics to create two classes capable of working with elements of any floating point type supported in Swift--that is, either Float
, Float80
, or Double
.
We want to create the following two classes:
MutableVector3D<T>
ImmutableVector3D<T>
It is a pretty simple task. We just have to replace Float
with the generic type parameter, T
, and change the class declaration to include the necessary generic...