Last active
January 9, 2020 10:41
-
-
Save janakmshah/cc017ab8decd580fcd70bcf3b56cf5e2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Refuelable { | |
func refuel() | |
} | |
protocol Drivable { | |
func drive() | |
} | |
struct Car: Refuelable, Drivable {} | |
//If we just include everything above this comment, the code will not compile. | |
//We need the default implementations below: | |
extension Refuelable { | |
func refuel() { | |
//Default refuel code here | |
} | |
} | |
extension Drivable { | |
func drive() { | |
//Default drive code | |
print("Default drive speed is 30mph") | |
} | |
} | |
struct CustomCar: Refuelable, Drivable { | |
func drive() { //Declaring this function within a struct that conforms to "Drivable" is equivalent to "override" for an inherited class type | |
print("The CustomCar drives at 100mph") | |
} | |
} | |
let car = Car() | |
car.drive() // Prints "Default drive speed is 30mph" | |
let customCar = CustomCar() | |
customCar.drive() // Prints "The CustomCar drives at 100mph |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment