Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // PROTOCOLS AND EXTENSIONS
- // A way describing what methods and properties something must have.
- // In this example, we create a protocol that dictates the existence of
- // an "id" property that can be read (get) or written (set).
- // Propert MUST have a get or get/set
- protocol Identifiable {
- var id: String { get set }
- }
- //create struct that conforms to Identifiable:
- struct User: Identifiable {
- var id: String
- }
- // We then create a function that accepts any Identifiable object:
- func displayID(thing: Identifiable) {
- print("My ID is \(thing.id)")
- }
- var greg = User(id: "389421")
- displayID(thing: greg) // "My ID is 389421"
- // PROTOCOL INHERITANCE
- // Unlike classes, you can inherit from multiple protocols
- // Note the syntax for functions
- protocol Payable {
- func calculateWages() -> Int
- }
- protocol NeedsTraining {
- func study()
- }
- protocol HasVacation {
- func takeVacation(days: Int)
- }
- // The above protocols could be brought together in one protocol:
- protocol Employee: Payable, NeedsTraining, HasVacation { }
- // EXTENSIONS
- // Allows us to add methods and computed properties to existing types
- // Adding method
- extension Int {
- func squared() -> Int {
- return self * self
- }
- }
- let number = 2
- number.squared() // 4
- // Adding computed property
- extension Int {
- var isEven: Bool {
- return self % 2 == 0
- }
- }
- number.isEven // true
- // PROTOCOL EXTENSIONS
- // Allow you to extend functionality to existing protocols
- // Allows us to add methods and computed properties to existing protocols
- // EG: Array and sets must conform to the Collections protocol.
- // We can use an extension to add a method that can be used by
- // all types that conform to this particular protocol
- let pythons = ["Eric", "Graham", "John", "Michael", "Terry", "Terry"]
- let beatles = Set(["John", "Paul", "George", "Ringo"])
- extension Collection {
- func summarize() {
- print("There are \(count) of us:")
- for name in self {
- print(name)
- }
- }
- }
- pythons.summarize() // "There are 6 of us: Eric..."
- beatles.summarize() // "There are 4 of us: John..."
- //PROTOCOL-ORIENTED PROGRAMMING
- /*
- 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.
- */
- // Create the protocol:
- protocol Recognizable {
- var id: String { get set }
- func identify()
- }
- // Use an extension to create the default method
- extension Recognizable {
- func identify() {
- print("My ID is \(id).")
- }
- }
- // Make struct that conforms to Recognizable protocol
- struct RecognizedUser: Recognizable {
- var id: String
- }
- let leck = RecognizedUser(id: "384429")
- leck.identify() // "384429"
Advertisement
Add Comment
Please, Sign In to add comment