如何在我班上创建的函数中使用我班级health
中声明的变量type
或init()
?
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
}
答案 0 :(得分:0)
这几乎是对我想要做的事情的重写。您的设计模式需要改变。这不是一个完美的解决方案,但希望您可以根据自己的需要进行修改!
import Foundation
import SpriteKit
class AbstractBoss: SKSpriteNode {
let bossType: Int
let bossHealth: Int
init(externalType: Int, externalHealth: Int, texture: SKTexture) {
bossHealth = externalHealth
bossType = externalType
super.init(texture: texture, color: .clear, size: texture.size())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class BossSante: AbstractBoss {
init() {
super.init(externalType: 1, externalHealth: 200, texture: SKTexture(imageNamed: "BossSanteImage"))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class BossDilbert: AbstractBoss {
init() {
super.init(externalType: 2, externalHealth: 2000, texture: SKTexture(imageNamed: "BossDilbertImage"))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class BossFactory {
func getBoss(withType bossType: Int) -> AbstractBoss {
//Determine which boss to return here and return it!
//Use Abstract boss in your collections and functions instead of SKSpriteNode
switch bossType {
case 1:
return BossSante()
default:
return BossDilbert()
}
}
}
let bossFactory = BossFactory()
//Use AbstractBoss in containers and functions instead of SKSpriteNode
let obj: AbstractBoss = bossFactory.getBoss(withType: 1)
obj.bossHealth
<强>摘要强>
答案 1 :(得分:0)
private(set) internal
访问修饰符(例如,请参阅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