Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. // note, P does not declare greet as requirement
  2.  
  3. protocol P {}
  4.  
  5. // ... but this does provide a "default" implementation
  6.  
  7. extension P {
  8. func greet() {print("hello")}
  9. }
  10.  
  11. // ... so if you have a class that overrides this
  12.  
  13. class C : P {
  14. func greet() {print("hello from C")
  15. }
  16. }
  17.  
  18. // but then use the protocol, rather than the class
  19.  
  20. func greeter(_ obj: P) {
  21. obj.greet()
  22. }
  23.  
  24. // then this will, confusingly IMHO, print "hello", not "hello from C"
  25.  
  26. greeter(C())
  27.  
  28. // ----
  29.  
  30. // However, if we define a protocol with this as a requirement
  31.  
  32. protocol Q {
  33. func greet()
  34. }
  35.  
  36. // ... and provide a default implementation
  37.  
  38. extension Q {
  39. func greet() {print("hello")}
  40. }
  41.  
  42. // ... and then override this default implementation
  43.  
  44. class D : Q {
  45. func greet() {print("hello from D")}
  46. }
  47.  
  48. // ... now this Q will honor any overrides that the class may implement
  49.  
  50. func anotherGreeter(_ obj: Q) {
  51. obj.greet()
  52. }
  53.  
  54. // ... this will now print "hello from D", as you'd expect it to
  55.  
  56. anotherGreeter(D())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement