gpt4 book ai didi

swift - 使用更少的参数在 Swift 中方便地初始化

转载 作者:可可西里 更新时间:2023-11-01 01:43:41 25 4
gpt4 key购买 nike

我正在尝试执行以下代码,但出现编译错误。我想在没有参数的情况下进行初始化,因为所有参数都设置为默认值,但我仍然需要使用父类(super class)的指定初始化程序。我希望能够为新的 AimNode 调用 AimNode()

class AimNode: SKSpriteNode {

override init() {
super.init(imageNamed: "aim")
}

required init(coder aDecoder: NSCoder) {

}
}

最佳答案

您的子类 (AimNode) 需要调用您的父类(super class) (SKSpriteNode) 的指定初始化程序。规则,如 Initializer Chaining 中所述快速编程指南的部分是:

To simplify the relationships between designated and convenience initializers, Swift applies the following three rules for delegation calls between initializers:

Rule 1 A designated initializer must call a designated initializer from its immediate superclass.

Rule 2 A convenience initializer must call another initializer from the same class.

Rule 3 A convenience initializer must ultimately call a designated initializer.

SKSpriteNode 的适当指定初始化程序是:

init(texture: SKTexture!, color: UIColor!, size: CGSize)

因此,您需要创建一个 SKTexture,选择颜色并设置大小。幸运的是,这相当简单:

class AimNode: SKSpriteNode {

// NOTE: I arbitrarily picked white for the color. I believe that's the default, but I don't know for sure.
override init() {
let texture = SKTexture(imageNamed: "aim")
super.init(texture: texture, color: UIColor.whiteColor(), size: texture.size())
}

// NOTE: You'll have to implement this too, if you don't have anything custom, you can just call the super implementation
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}

关于swift - 使用更少的参数在 Swift 中方便地初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26198777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com