私は、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
最初の 3 つの print() 行はまさに私が期待し、望んでいるものですが、最後の 3 行は本当に困惑します。conforms() はプロトコル要件であるため、上の 3 行と同じでなければなりません。しかし、conforms() がプロトコル拡張に実装されているが、プロトコル要件としてリストされていないかのように動作します。これについては、The Swift Programming Language リファレンス マニュアルには何もありません。この WWDC のビデオはちょうど 30:40 で、私の主張を証明しています。
それで、私は何か間違ったことをしたのですか、機能を誤解したのですか、それとも Swift 3 でバグを見つけましたか?