Created
December 20, 2019 09:16
-
-
Save JagCesar/8cd4207c655d191f4d88fc3af98484d1 to your computer and use it in GitHub Desktop.
Example of protocol extensions functionality
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol Nameable { | |
/// This func is required by anyone who conforms to this protocol | |
func lastName() -> String | |
} | |
extension Nameable { | |
/// This will be the default implementation if the conforming class doesn't override this implementation. | |
func firstname() -> String { | |
return "John Appleseed" | |
} | |
} | |
class Person { } | |
extension Person: Nameable { | |
/// We don't get an error if we don't declare this function and there is no way to call the implementation in the | |
/// protocol extension. There is no `override` prefix which would make it easier to understand that we're overriding | |
/// the default implementation and not declaring a new function in this extension. | |
func firstname() -> String { | |
return "Tim" | |
} | |
/// Compiler error if this function is missing. This is as it should be. | |
func lastName() -> String { | |
return "Cook" | |
} | |
} | |
extension Nameable where Self: Animal { | |
/// These functions will override the default implementation of `firstName()` and `lastName()` in the `Nameable` extension but only for instances of | |
/// `Animal` which don't override any of these function. And same thing here, no `override` prefix that makes it clear that we're | |
/// overriding a function and there is no way to call `super.firstName()`. | |
func firstname() -> String { | |
return "Fifi" | |
} | |
func lastName() -> String { | |
return "A last name on a pet? 😂" | |
} | |
} | |
class Animal { } | |
extension Animal: Nameable { | |
/// This implementation will override the implementation on row #69 and row #45. Once again no way to quickly see which code we're overriding and not possible | |
/// to call `super.firstName()`. | |
func firstname() -> String { | |
return "Ferguson" | |
} | |
func lastName() -> String { | |
return "Bishop" | |
} | |
} | |
let friend = Person() | |
friend.firstname() | |
friend.lastName() | |
let pet = Animal() | |
pet.firstname() | |
pet.lastName() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment