如何在我的函数中使用类中 init()
中声明的变量 health
或 type
在我的类(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
}
最佳答案
- 如果您想稍后访问它们,则必须将传递给初始值设定项的参数存储为实例属性。
- 您不必使用专用函数来从类中获取值,只需访问属性即可。
- 如果您希望属性从外部不可变,请应用
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/