0
protocol Sound { func makeSound() }

extension Sound {  
   func makeSound() { 
     print("Wow") 
   } 
}

protocol Flyable {
   func fly()
}

extension Flyable { 
    func fly() {
        print("✈️") 
    }
}

class Airplane: Flyable { }

class Pigeon: Sound, Flyable { }

class Penguin: Sound { }

let pigeon = Pigeon()
pigeon.fly()  // prints ✈️
pigeon.makeSound() // prints Wow

the above code works fine but, I need to print different types of sound (I.E). if I call the airplane.fly() it should print me ("something different") . and same for penguin

nycynik
  • 7,371
  • 8
  • 62
  • 87
  • 2
    The indentation here is a bit irregular. Remember that helps us understand not only the meaning of your code, but your intent, as sometimes mistakes boil down to forgetting to add some syntax. Please take the time to clean that up before posting. – tadman Sep 17 '18 at 20:12
  • Possible duplicate of [Swift: Test class type in switch statement](https://stackoverflow.com/questions/25724527/swift-test-class-type-in-switch-statement) – nycynik Sep 17 '18 at 20:23
  • So what do you mean "I want to use switch". Do you mean a switch statement? How does that relate to your question? – Duncan C Sep 17 '18 at 22:05

1 Answers1

3

Provide fly() for the Airplane class:

class Airplane: Flyable {
    func fly() {
        print("something different")
    }
}

let airBus: Airplane = Airplane()
airBus.fly()
//prints "something different"

You can do the same for the Penguin class:

class Penguin: Sound {
    func makeSound() {
        print("squawk")
    }
}

let  = Penguin()
.makeSound()
//prints "squawk"

The functions you are providing are default implementations of the protocol. If a type doesn't override the function, it will adopt the default implementation. You can find more in the docs:

You can use protocol extensions to provide a default implementation to any method or computed property requirement of that protocol. If a conforming type provides its own implementation of a required method or property, that implementation will be used instead of the one provided by the extension.

ielyamani
  • 17,807
  • 10
  • 55
  • 90