根据Swift Book:
Rule 1
If your subclass doesn’t define any designated initializers,it automatically inherits all of its superclass designated initializers.
Rule 2
If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1,or by providing a custom implementation as part of its deFinition—then it automatically inherits all of the superclass convenience initializers.”
但是,以下类不起作用:
class MyShapeNode : SKShapeNode { convenience init(squareOfSize value: CGFloat) { self.init(rectOfSize: CGSizeMake(value,value)) } }
相反,我得到:
Playground execution Failed: error: <REPL>:34:9: error: use of 'self' in delegating initializer before self.init is called self.init(rectOfSize: CGSizeMake(value,value)) ^ <REPL>:34:14: error: use of 'self' in delegating initializer before self.init is called self.init(rectOfSize: CGSizeMake(value,value)) ^ <REPL>:35:5: error: self.init isn't called on all paths in delegating initializer }
我的理解是,MyShapeNode应该继承所有的SKShapeNode的方便的初始化器,因为我没有实现任何我自己的指定的初始化器,并且因为我的方便的初始化器调用了init(rectOfSize),另一个方便的初始化器,这应该工作。我究竟做错了什么?
解决方法
我在游乐场测试了以下内容,并按预期工作:
class RectShape: NSObject { var size = CGSize(width: 0,height: 0) convenience init(rectOfSize size: CGSize) { self.init() self.size = size } } class SquareShape: RectShape { convenience init(squareOfSize size: CGFloat) { self.init(rectOfSize: CGSize(width: size,height: size)) } }
RectShape从NSObject继承,并没有定义任何指定的初始化程序。因此,根据规则1,它继承NSObject的所有指定的初始化器。我在实施过程中提供的方便的初始化程序在进行安装之前正确地委派给指定的初始化程序。
SquareShape继承自RectShape,不提供指定的初始化程序,并且按照规则1再次继承了所有的SquareShape指定的初始化程序。根据规则2,它还继承了RectShape中定义的方便初始化器。最后,SquareShape中定义的方便的初始化器正确地委托给继承的方便初始化器,然后再次委托给继承的指定的初始化器。
所以,考虑到你没有做错什么,我的例子如预期的那样工作,我推断出以下假设:
由于SKShapeNode是在Objective-C中编写的,所以规定“每个方便的初始化程序必须从同一个类调用另一个初始化程序”不被该语言强制执行。因此,也许SKShapeNode的方便初始化器实际上并不调用指定的初始化程序。因此,即使MyShapeNode子类继承了预期的方便初始化器,它们也不会正确地委托给继承的指定的初始化程序。
但是,这只是一个假设。我可以确认的是,机械师按照我自己创造的两个班级的预期工作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。