swift - Designated Initializer & Convenience Initializers

swift - Designated Initializer & Convenience Initializers,第1张

概述Designated initializers tend to set all of the properties up and let the user send in values for each. A convenience initializer often has some of those hard coded, and thus can take less parameters T

Designated initializers tend to set all of the propertIEs up and let the user send in values for each. A convenIEnce initializer often has some of those hard coded,and thus can take less parameters

To simplify the relationships between designated and convenIEnce initializers,Swift applIEs the following three rules for delegation calls between initializers:

Rule 1
A designated initializer must call a designated initializer from its immediate superclass.

Rule 2
A convenIEnce initializer must call another initializer from the same class.

Rule 3
A convenIEnce initializer must ultimately call a designated initializer.

A simple way to remember this is:

Designated initializers must always delegate up.ConvenIEnce initializers must always delegate across.

下面举例说明以上几点:

首先我们创建一个子类继承UIVIEw,添加自己的一个init方法(Designated initializers):

init(frame: CGRect,bgcolor: UIcolor,tag: Int,superVIEw: UIVIEw) {}

在这里,我们需要遵循Rule 1,调用父类的Designated initializers

init(frame: CGRect,superVIEw: UIVIEw) { super.init(frame:frame) // not super.init() self.backgroundcolor = bgcolor self.tag = tag superVIEw.addSubvIEw(self) }

接下来,我们再创建两个ConvenIEnce initializers

convenIEnce init(bgcolor:UIcolor) {   self.init(frame:CGRectZero,bgcolor:bgcolor)//Rule 2}convenIEnce init(frame: CGRect,bgcolor:UIcolor) {   self.init(frame: frame,bgcolor:bgcolor,tag: 0)//Rule 3}

使用Designated Initializer的好处:

在修改代码之前,应该想清楚是否需要删除原有代码。类似这种扩展,旧的接口可以留下来,然后在其中调用多参数的Designated Initializer。保证良好的编写Designated Initializer的风格,可以让我们节约很多时间,避免潜藏的BUG出现

总结

以上是内存溢出为你收集整理的swift - Designated Initializer & Convenience Initializers全部内容,希望文章能够帮你解决swift - Designated Initializer & Convenience Initializers所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1078351.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存