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上面的代码运行良好,但我需要打印不同类型的声音(即)。如果我调用airplane.fly(),它应该打印我(“一些不同的东西”)。企鹅也是一样
发布于 2018-09-18 04:20:06
为Airplane类提供fly():
class Airplane: Flyable {
func fly() {
print("something different")
}
}
let airBus: Airplane = Airplane()
airBus.fly()
//prints "something different"您可以对Penguin类执行相同的操作:
class Penguin: Sound {
func makeSound() {
print("squawk")
}
}
let = Penguin()
.makeSound()
//prints "squawk"您提供的函数是协议的默认实现。如果类型没有覆盖函数,它将采用默认实现。您可以在docs中找到更多信息
您可以使用协议扩展为该协议的任何方法或计算属性要求提供默认实现。如果一致类型提供了所需方法或属性的自己的实现,则将使用该实现而不是扩展提供的实现。
https://stackoverflow.com/questions/52375022
复制相似问题