I am learning all about swift, OOP, and POP. I have been mixing them together to make an abstract base class when I came across some unexpected behavior. It is best expressed in code, I will show it working as expected, and then as unexpected (to me at least). The code is long, but simple. Here it is working properly:
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() }
And here is the output:
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
This is exactly as I would suspect. But I ran into this problem in my app when the first class didn't have a custom implementation of conforms(), like this:
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() }
Notice here that TheUniverse does not have a custom implementation of conforms(). Here is the output:
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
The first three print() lines are exactly what I expect and want, but the last three really baffle me. Since conforms() is a protocol requirement, they should be identical to the top three lines. But I am getting behavior as if conforms() was implemented in the protocol extension, but not listed as a protocol requirement. There is nothing about this in The Swift Programming Language reference manual. And this WWDC video at exactly 30:40 in proves my point.
So, have I done something wrong, misunderstood the functionality, or have I found a bug in swift 3?