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.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...