
根据Swift Book:
Rule 1If your subclass doesn’t define any designated initializers,it automatically inherits all of its superclass designated initializers.
Rule 2If 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子类继承了预期的方便初始化器,它们也不会正确地委托给继承的指定的初始化程序。
但是,这只是一个假设。我可以确认的是,机械师按照我自己创造的两个班级的预期工作。
总结以上是内存溢出为你收集整理的ios – 在Swift子类中添加方便初始化器全部内容,希望文章能够帮你解决ios – 在Swift子类中添加方便初始化器所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)