GregLeck

Protocols and Extensions

Oct 3rd, 2019
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.85 KB | None | 0 0
  1. // PROTOCOLS AND EXTENSIONS
  2. // A way describing what methods and properties something must have.
  3. // In this example, we create a protocol that dictates the existence of
  4. // an "id" property that can be read (get) or written (set).
  5. // Propert MUST have a get or get/set
  6. protocol Identifiable {
  7.     var id: String { get set }
  8. }
  9.  
  10. //create struct that conforms to Identifiable:
  11. struct User: Identifiable {
  12.     var id: String
  13. }
  14.  
  15. // We then create a function that accepts any Identifiable object:
  16. func displayID(thing: Identifiable) {
  17.     print("My ID is \(thing.id)")
  18. }
  19.  
  20. var greg = User(id: "389421")
  21. displayID(thing: greg)          // "My ID is 389421"
  22.  
  23. // PROTOCOL INHERITANCE
  24. // Unlike classes, you can inherit from multiple protocols
  25. // Note the syntax for functions
  26. protocol Payable {
  27.     func calculateWages() -> Int
  28. }
  29.  
  30. protocol NeedsTraining {
  31.     func study()
  32. }
  33.  
  34. protocol HasVacation {
  35.     func takeVacation(days: Int)
  36. }
  37.  
  38. // The above protocols could be brought together in one protocol:
  39. protocol Employee: Payable, NeedsTraining, HasVacation { }
  40.  
  41. // EXTENSIONS
  42. // Allows us to add methods and computed properties to existing types
  43.  
  44. // Adding method
  45. extension Int {
  46.     func squared() -> Int {
  47.         return self * self
  48.     }
  49. }
  50.  
  51. let number = 2
  52. number.squared()            // 4
  53.  
  54. // Adding computed property
  55. extension Int {
  56.     var isEven: Bool {
  57.         return self % 2 == 0
  58.     }
  59. }
  60.  
  61. number.isEven               // true
  62.  
  63. // PROTOCOL EXTENSIONS
  64. // Allow you to extend functionality to existing protocols
  65. // Allows us to add methods and computed properties to existing protocols
  66. // EG: Array and sets must conform to the Collections protocol.
  67. // We can use an extension to add a method that can be used by
  68. // all types that conform to this particular protocol
  69. let pythons = ["Eric", "Graham", "John", "Michael", "Terry", "Terry"]
  70. let beatles = Set(["John", "Paul", "George", "Ringo"])
  71.  
  72. extension Collection {
  73.     func summarize() {
  74.         print("There are \(count) of us:")
  75.        
  76.         for name in self {
  77.             print(name)
  78.         }
  79.     }
  80. }
  81.  
  82. pythons.summarize() // "There are 6 of us: Eric..."
  83. beatles.summarize() // "There are 4 of us: John..."
  84.  
  85. //PROTOCOL-ORIENTED PROGRAMMING
  86. /*
  87.  Protocol-oriented programming is the practice of designing your app architecture as a series of protocols, then using protocol extensions to provide default method implementations.
  88.  */
  89. // Create the protocol:
  90. protocol Recognizable {
  91.     var id: String { get set }
  92.     func identify()
  93. }
  94.  
  95. // Use an extension to create the default method
  96. extension Recognizable {
  97.     func identify() {
  98.         print("My ID is \(id).")
  99.     }
  100. }
  101.  
  102. // Make struct that conforms to Recognizable protocol
  103. struct RecognizedUser: Recognizable {
  104.     var id: String
  105. }
  106.  
  107. let leck = RecognizedUser(id: "384429")
  108. leck.identify()         // "384429"
Advertisement
Add Comment
Please, Sign In to add comment