这里我的代码不起作用
编辑:
所以它会很好
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 }
解决方法
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 } }
> init(aTitle:String?,aImageName:String?)无法调用init(aTitle :)并仍然是指定的初始化程序,它必须是一个便利初始化程序.
> self.init必须在init之前的任何其他内容(aTitle:String?,aImageName:String?).
>初始化程序必须传递参数名称self.init(aTitle)必须是self.init(aTitle:aTitle).
作为旁注,我删除了不需要的分号,并首先将super.init()用于样式原因.
希望有所帮助.
UPDATE
要遵循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 }
有时您可能需要多次指定的初始化程序,例如UIView,但这应该是一个例外,而不是规则.
更新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.
The Designated Initializer
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.