我正在学习有关 swift、OOP 和 POP 的所有知识。当我遇到一些意想不到的行为时,我一直在将它们混合在一起以创建一个抽象基类。它最好用代码来表达,我将展示它按预期工作,然后按预期工作(至少对我来说)。代码很长,但很简单。在这里它工作正常:
protocol GodsWill { func conforms() }
extension GodsWill { func conforms() { print("Everything conforms to God's Will") } }
class TheUniverse: GodsWill { func conforms() { print("The Universe conforms to God's Will") } }
class Life: TheUniverse { override func conforms() { print("Life conforms to God's Will") } }
class Humans: Life { override func conforms() { print("Though created by God, Humans think they know better") } }
let universe = TheUniverse()
let life = Life()
let humans = Humans()
universe.conforms()
life.conforms()
humans.conforms()
print("-------------------------")
let array:[GodsWill] = [universe,life,humans]
for item in array { item.conforms() }
这是输出:
The Universe conforms to God's Will
Life conforms to God's Will
Though created by God, Humans sometimes think they know better
-------------------------
The Universe conforms to God's Will
Life conforms to God's Will
Though created by God, Humans sometimes think they know better
这正是我所怀疑的。但是当第一个类没有 conforms() 的自定义实现时,我在我的应用程序中遇到了这个问题,如下所示:
protocol GodsWill { func conforms() }
extension GodsWill { func conforms() { print("Everything conforms to God's Will") } }
class TheUniverse: GodsWill { }
class Life: TheUniverse { func conforms() { print("Life conforms to God's Will") } }
class Humans: Life { override func conforms() { print("Though created by God, Humans sometimes think they know better") } }
let universe = TheUniverse()
let life = Life()
let humans = Humans()
universe.conforms()
life.conforms()
humans.conforms()
print("-------------------------")
let array:[GodsWill] = [universe,life,humans]
for item in array { item.conforms() }
请注意,TheUniverse 没有 conforms() 的自定义实现。这是输出:
Everything conforms to God's Will
Life conforms to God's Will
Though created by God, Humans sometimes think they know better
-------------------------
Everything conforms to God's Will
Everything conforms to God's Will
Everything conforms to God's Will
前三行 print() 正是我所期望和想要的,但后三行真的让我感到困惑。由于 conforms() 是协议要求,因此它们应该与前三行相同。但是我得到的行为好像 conforms() 是在协议扩展中实现的,但没有列为协议要求。The Swift Programming Language 参考手册中没有关于此的内容。这段 WWDC 视频正好在30:40证明了我的观点。
那么,是我做错了什么,误解了功能,还是在 swift 3 中发现了一个错误?