Swift Protocol Inheritance & Generic functions

心已入冬 提交于 2019-12-01 17:02:11

That smells like a compiler bug for one simple reason: makerB is a variable of B type, but it is assigned an instance of A. This should not be possible, and in fact if you try to print, and more generally to access to, the another_stored property of the makerB variable, a runtime exception is raised, and I wouldn't expecting nothing else.

That's because if B is a subclass of A, an instance of A cannot be assigned to a variable of B type (whereas the opposite is possible).

Assigning a variable of A type to a variable of B type is possible though, but only under these conditions:

  • an explicit downcast from A to B is done (the compiler should error otherwise)
  • the instance referenced by the A variable is actually an instance of B (a runtime exception should be raised otherwise)

Note that the compiler didn't just fail to call the correct initializer - it called the initializer of another class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!