gpt4 book ai didi

swift - 我想在扩展中使用开关

转载 作者:行者123 更新时间:2023-11-28 10:37:59 25 4
gpt4 key购买 nike

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

上面的代码工作正常,但我需要打印不同类型的声音 (I.E)。如果我调用 airplane.fly() 它应该打印 me ("something different") 。企鹅也一样

最佳答案

为 Airplane 类提供 fly():

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

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

你可以为企鹅类做同样的事情:

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

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

您提供的功能是协议(protocol)的默认实现。如果一个类型没有覆盖函数,它将采用默认实现。您可以在 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.

关于swift - 我想在扩展中使用开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52375022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com