我将在
Swift中重载init方法如何实现它?
@H_502_2@这里我的代码不起作用
@H_502_2@代码删除
@H_502_2@编辑:
@H_502_2@所以它会很好
override init() { super.init(); } init(title:String?) { super.init(); self.title = title } convenience init(title:String?,imageName:String?) { self.init(title:title) self.imageName = imageName } convenience init(title:String?,imageName:String?,contentKey:String?) { self.init(title:title,imageName:imageName) self.contentKey = contentKey }
解决方法
我将样品插入操场,以下是我如何使用它:
> self.init必须在init之前的任何其他内容(aTitle:String?,aImageName:String?).
>初始化程序必须传递参数名称self.init(aTitle)必须是self.init(aTitle:aTitle). @H_502_2@作为旁注,我删除了不需要的分号,并首先将super.init()用于样式原因. @H_502_2@希望有所帮助. @H_502_2@UPDATE @H_502_2@要遵循Apple的建议,应该只指定一个,其余应该是便利初始化器.例如,如果您决定init(aTitle:String?)应该是指定的初始化程序,那么代码应如下所示:
class Y { } class X : Y { var title: String? var imageName: String? override init() { } init(aTitle:String?) { super.init() self.title = aTitle } convenience init(aTitle:String?,aImageName:String?) { self.init(aTitle: aTitle) self.imageName = aImageName } }@H_502_2@> init(aTitle:String?,aImageName:String?)无法调用init(aTitle :)并仍然是指定的初始化程序,它必须是一个便利初始化程序.
> self.init必须在init之前的任何其他内容(aTitle:String?,aImageName:String?).
>初始化程序必须传递参数名称self.init(aTitle)必须是self.init(aTitle:aTitle). @H_502_2@作为旁注,我删除了不需要的分号,并首先将super.init()用于样式原因. @H_502_2@希望有所帮助. @H_502_2@UPDATE @H_502_2@要遵循Apple的建议,应该只指定一个,其余应该是便利初始化器.例如,如果您决定init(aTitle:String?)应该是指定的初始化程序,那么代码应如下所示:
convenience override init() { self.init(aTitle: nil) // A convenience initializer calls the designated initializer. } init(aTitle:String?) { super.init() // Only the designated initializer calls super.init. self.title = aTitle } convenience init(aTitle:String?,aImageName:String?) { self.init(aTitle: aTitle) // A convenience initializer calls the designated initializer. self.imageName = aImageName }@H_502_2@有时您可能需要多次指定的初始化程序,例如UIView,但这应该是一个例外,而不是规则. @H_502_2@更新2 @H_502_2@类应该有一个指定的初始化程序.便利初始化程序将(最终)调用指定的初始化程序. @H_502_2@Initialization
@H_502_2@A class may have multiple initializers. This occurs when the initialization data can take varied forms or where certain initializers,as a matter of convenience,supply default values. In this case,one of the initialization methods is called the designated initializer,which takes the full complement of initialization parameters.@H_502_2@Multiple initializers
The Designated Initializer
@H_502_2@The initializer of a class that takes the full complement of initialization parameters is usually the designated initializer. The designated initializer of a subclass must invoke the designated initializer of its superclass by sending a message to super. The convenience (or secondary) initializers—which can include init—do not call super. Instead they call (through a message to self) the initializer in the series with the next most parameters,supplying a default value for the parameter not passed into it. The final initializer in this series is the designated initializer.