gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:41:01 25 4
gpt4 key购买 nike

如何在我的函数中使用类中 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/

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