xcode – Swift重载init()

我将在 Swift中重载init方法如何实现它?

这里我的代码不起作用

代码删除

编辑:

所以它会很好

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

类应该有一个指定的初始化程序.便利初始化程序将(最终)调用指定的初始化程序.

Initialization

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.

Multiple initializers

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.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...