swift - 使用类的 init() 中声明的变量 - Swift 4

标签 swift class initialization

如何在我的函数中使用类中 init() 中声明的变量 healthtype在我的类(class)中创建过吗?

import Foundation
import SpriteKit

class Boss:  SKSpriteNode {

    init(type: Int, health: Int) {

        let texture: SKTexture!

        if type == 1 {
            texture = SKTexture(imageNamed: "Boss1")
        }
        else if type == 2 {
            texture = SKTexture(imageNamed: "Boss2")
        }
        else {
            texture = SKTexture(imageNamed: "Boss3")
        }

        super.init(texture: texture , color: .clear, size: texture.size())
        zPosition = 2
    }

    func bossSante() -> Int {
            return health
    }


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

//I would like to make a function that will return the value of "health"

    func bossSante()  {
        return health
    }

最佳答案

  1. 如果您想稍后访问它们,则必须将传递给初始值设定项的参数存储为实例属性。
  2. 您不必使用专用函数来从类中获取值,只需访问属性即可。
  3. 如果您希望属性从外部不可变,请应用 private(set) inside 访问修饰符(例如,请参阅 type 属性)。

总结一下:

class Boss: SKSpriteNode {

  private(set) var type: Int
  var health: Int

  init(type: Int, health: Int) {
    self.type = type
    self.health = health

    let texture = ...
    super.init(texture: texture , color: .clear, size: texture.size())
  }
}

let boss = Boss(type: 1, health: 100) // type and health will be stored as properties of boss
print(boss.health) // access boss' health
boss.type = 2 // won't compile since `type` becomes immutable from an external code

关于swift - 使用类的 init() 中声明的变量 - Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49287623/

相关文章:

java - 使用 null 初始化字符串数组中的特定索引

java - log4j2 在 Web 应用程序中错误启动

ios - 从父 UIView 移除 CALayers

ios - 根据项目名称和详细信息从firebase中检索用户的信息-Swift项目

python - 如何在Python中实现引用调用结构

c++ - 使用非前缀成员变量时如何命名构造函数参数?

swift - 从通讯录中获取 kABAddressCountryCodeKey

ios - 在 Swift 3 中,如何在转换到另一个 SKView 时传递变量?

c++ - 编译似乎不遵循不同 operator= 重载之间的正确路径

c++ - 父类的复制构造函数中的嵌套类缺少默认构造函数