Sam Sam - 10 months ago 52
Swift Question

Using a class (or instance) property inside of another classes initilizer in swift

I'm relatively new to Swift, and I wanted to know if there was a way to reference a class's property inside of a separate class initializer? For example: if I have a class

Person
with the property
position
, is there a way to initialize a
Pants
class such that its
position
is the same as
Person
's? Here's my code:

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")
}
}

}


At first I tried referencing
aPerson
which is an instance of
Person
but I received the error:
Instance member aPerson cannot be used on type GameScene
. I think understand why it doesn't make much sense to reference an instance in this case- as the instance may not exist by the time of reference? But I don't really know what this error message means- any clarification would be great. I then thought to use a
static
getter method within the
Person
class that just returned it's position property. This also doesn't seem to work. Any suggestions would be awesome!

Answer Source

One solution is to add a parameter to your initializer (as suggested by Paul Griffiths in a comment above):

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")
    }
}

Then wherever you want to create a Pants instance, you must pass a person:

let somePerson = Person()
let pants = Pants(aPerson: somePerson)