Skip to content

Instantly share code, notes, and snippets.

@janakmshah
Last active January 9, 2020 10:41
Show Gist options
  • Save janakmshah/cc017ab8decd580fcd70bcf3b56cf5e2 to your computer and use it in GitHub Desktop.
Save janakmshah/cc017ab8decd580fcd70bcf3b56cf5e2 to your computer and use it in GitHub Desktop.
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