Guest User

Untitled

a guest
Nov 20th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. protocol PointProtocol {}
  2.  
  3. class Point1D: PointProtocol {
  4. let x: Double
  5.  
  6. init(x: Double) {
  7. self.x = x
  8. }
  9.  
  10. func description() -> String {
  11. return "\(x)"
  12. }
  13. }
  14.  
  15. class Point2D: Point1D {
  16. let y: Double
  17.  
  18. init(x: Double, y: Double) {
  19. self.y = y
  20. super.init(x: x)
  21. }
  22.  
  23. func product() -> Double {
  24. return x * y
  25. }
  26.  
  27. override func description() -> String {
  28. return "\(x), \(y)"
  29. }
  30. }
  31.  
  32. class Point3D: Point2D {
  33. let z: Double
  34.  
  35. init(x: Double, y: Double, z: Double) {
  36. self.z = z
  37. super.init(x: x, y: y)
  38. }
  39.  
  40. override func description() -> String {
  41. return "\(x), \(y), \(z)"
  42. }
  43.  
  44. func sum() -> Double {
  45. return x + y + z
  46. }
  47. }
  48.  
  49. // 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.
  50. func twoToTwo<T>(p: T) -> T where T: PointProtocol {
  51. return p
  52. }
  53.  
  54. let p123: Point3D = Point3D(x: 1, y: 2, z: 3)
  55.  
  56. 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
  57.  
  58. 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
  59.  
  60. print(p1.product()) // Compiler error. Although p1 points to a Point3D type, there is no method product in the Point1D lookup table
  61.  
  62. 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.
  63.  
  64. 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