gpt4 book ai didi

ios - 当init()也初始化成员变量并引用 "self"时super.init()放在哪里

转载 作者:搜寻专家 更新时间:2023-11-01 06:18:04 24 4
gpt4 key购买 nike

我正在学习 Swift,现在我有了这段代码:

import SpriteKit
import GameplayKit

class Player: GKEntity {

var spriteComponent : SpriteComponent

init(imageName: String) {
super.init() // gives error: self.spriteComponent not initialized at super.init call
let texture = SKTexture(imageNamed: imageName)
spriteComponent = SpriteComponent(entity: self, texture: texture, size: texture.size())

// super.init() Placing it here gives error on line above: "self used before super.init() call"
addComponent(spriteComponent)
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

}

我已经看到了关于此的其他问题,但我无法想象我必须在 SpriteComponent 中创建一个虚拟初始化程序(参数为零)并像这样调用它:

var spriteComponent = SpriteComponent()

为了在引用“self”之前调用 super.init()

谁能解释一下为什么我必须跳这种愚蠢的踢踏舞?肯定有更好的方法来做对吗? Swift 不可能是这样的 *&%&/(% 对吗?

最佳答案

在调用 super.init() 之前必须初始化子类中声明的所有非可选属性

所以你有两种方法来解决这些问题:

  1. 将属性类型更改为可选(SpriteComponent?SpriteComponent!)。
  2. 在声明属性时或在调用 super.init 之前在初始化程序中初始化每个属性

在您的情况下,第一个选项更适合。

您可以在此处找到有关 Swift 两阶段初始化的更多信息: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html

本教程也可能有帮助:(向子类添加属性 段落): https://www.raywenderlich.com/121603/swift-tutorial-initialization-part-2

关于ios - 当init()也初始化成员变量并引用 "self"时super.init()放在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39867983/

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