快速初始化和便捷实例中init和init之间的区别是什么 [英] What is the difference between convenience init vs init in swift, explicit examples better

查看:148
本文介绍了快速初始化和便捷实例中init和init之间的区别是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解两者之间的区别,或者便捷初始化的目的. 谢谢

解决方案

标准init:

指定的初始值设定项是类的主要初始值设定项.一种 指定的初始化程序完全初始化由引入的所有属性 该类并调用适当的超类初始化器以继续 超类链的初始化过程.

convenience init:

便捷初始化器是次要的,支持用于 班级.您可以定义一个便捷初始化程序来调用指定的 与便捷初始化程序来自同一类的初始值设定项,其中一些 指定的初始值设定项的参数设置为默认值.你可以 还定义了一个便利的初始化程序来创建该类的实例 针对特定的用例或输入值类型.

根据快速文档

简而言之,这意味着您可以使用便捷的初始化程序来更快,更方便"地调用指定的初始化程序.因此,便利的初始化程序要求使用self.init而不是在指定的初始化程序的替代中可能看到的super.init.

伪代码示例:

init(param1, param2, param3, ... , paramN) {
     // code
}

// can call this initializer and only enter one parameter,
// set the rest as defaults
convenience init(myParamN) {
     self.init(defaultParam1, defaultParam2, defaultParam3, ... , myParamN)
}

在创建自定义视图时,我会经常使用这些视图,并且这些视图具有较长的初始化程序(主要是默认值).文档比我做得更好,请解释一下!

I am having troubles to understand the difference between both, or the purpose of the convenience init. thanks

解决方案

Standard init:

Designated initializers are the primary initializers for a class. A designated initializer fully initializes all properties introduced by that class and calls an appropriate superclass initializer to continue the initialization process up the superclass chain.

convenience init:

Convenience initializers are secondary, supporting initializers for a class. You can define a convenience initializer to call a designated initializer from the same class as the convenience initializer with some of the designated initializer’s parameters set to default values. You can also define a convenience initializer to create an instance of that class for a specific use case or input value type.

per the Swift Documentation

In a nutshell, this means that you can use a convenience initializer to make calling a designated initializer faster and more "convenient". So convenience initializers require the use of self.init instead of the super.init you might see in an override of a designated initializer.

pseudocode example:

init(param1, param2, param3, ... , paramN) {
     // code
}

// can call this initializer and only enter one parameter,
// set the rest as defaults
convenience init(myParamN) {
     self.init(defaultParam1, defaultParam2, defaultParam3, ... , myParamN)
}

I use these a lot when creating custom views and such that have long initializers with mainly defaults. The docs do a better job explaining than I can, check them out!

这篇关于快速初始化和便捷实例中init和init之间的区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆