Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- protocol PointProtocol {}
- class Point1D: PointProtocol {
- let x: Double
- init(x: Double) {
- self.x = x
- }
- func description() -> String {
- return "\(x)"
- }
- }
- class Point2D: Point1D {
- let y: Double
- init(x: Double, y: Double) {
- self.y = y
- super.init(x: x)
- }
- func product() -> Double {
- return x * y
- }
- override func description() -> String {
- return "\(x), \(y)"
- }
- }
- class Point3D: Point2D {
- let z: Double
- init(x: Double, y: Double, z: Double) {
- self.z = z
- super.init(x: x, y: y)
- }
- override func description() -> String {
- return "\(x), \(y), \(z)"
- }
- func sum() -> Double {
- return x + y + z
- }
- }
- // Accepts Point1D, Point2D, or Point3D reference returns a reference of the type passed in, which may be assigned to Point1D, Point2D, or Point3D variable, regardless of what was passed in.
- func twoToTwo<T>(p: T) -> T where T: PointProtocol {
- return p
- }
- let p123: Point3D = Point3D(x: 1, y: 2, z: 3)
- print(twoToTwo(p: p123).product()) // 2.0. product found in the lookup table of Point2D, which is the superclass of the return type for twoToTwo when passed p of type Point3D
- let p1: Point1D = twoToTwo(p: p123) // Returns a reference of type Point3D, assigned to a variable of type Point1D, which points to an object of type Point3D
- print(p1.product()) // Compiler error. Although p1 points to a Point3D type, there is no method product in the Point1D lookup table
- print(p1.description()) // 1.0, 2.0, 3.0. The variable p1 is type Point1D, which has description in its lookup table. When looking up the method, Point3D.description is the first method found.
- print(p1.sum()) // Compiler error. Although the object referenced by p1 contains x, y, and z, the variable is of type Point1D, for which there is no function sum in the method lookup table.
Add Comment
Please, Sign In to add comment