我对 Swift 比较陌生,我想知道是否有办法在单独的类初始化器中引用类的属性?例如:如果我有一个 Person
类,其属性为 position
,有没有办法初始化一个 Pants
类,使其 position
与 Person
的相同吗?这是我的代码:
class Pants:SKSpriteNode{
init(){
let pants = SKTexture(imageNamed: "Sprites/pants.jpg")
pants.setScale(0.5)
super.init(texture: pants, color: UIColor.clearColor(), size: pants.size())
//self.position.x = aPerson.position.x + (aPerson.size.width / 2)
//self.position.y = aPerson.position.y - (aPerson.size.height * 0.04)
self.position = Person.getPos()//CGPoint(x: 200,y: 200)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
起初我尝试引用 aPerson
,它是 Person
的一个实例,但我收到错误:Instance member aPerson cannot be used on type GameScene
。我想理解为什么在这种情况下引用一个实例没有多大意义——因为在引用时该实例可能不存在?但我真的不知道这个错误消息是什么意思——任何澄清都会很好。然后我想在刚刚返回其位置属性的 Person
类中使用 static
getter 方法。这似乎也行不通。任何建议都会很棒!
最佳答案
一种解决方案是向您的初始化程序添加一个参数(正如 Paul Griffiths 在上面的评论中所建议的):
class Pants: SKSpriteNode {
init(aPerson: Person) {
let pants = SKTexture(imageNamed: "Sprites/pants.jpg")
pants.setScale(0.5)
super.init(texture: pants, color: UIColor.clearColor(), size: pants.size())
self.position.x = aPerson.position.x + (aPerson.size.width / 2)
self.position.y = aPerson.position.y - (aPerson.size.height * 0.04)
self.position = aPerson.getPos()//CGPoint(x: 200,y: 200)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
然后无论你想在哪里创建一个Pants
实例,你都必须传递一个人:
let somePerson = Person()
let pants = Pants(aPerson: somePerson)
关于swift - 在 swift 中使用另一个类初始值设定项中的类(或实例)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38624398/