JeffD
JeffD

Reputation: 89

Passing variables between functions in swift

So ive been writing a game in swift using SpriteKit, and i'm having trouble understanding how variables are handled in swift. I'm trying to update a variable I declare at the beginning of my GameScene class again in the touchesBegan function that comes later. However, the problem i'm having is that the variable is never updated (I know this because in the didMoveToView function, the variable is used to direct the rotation of a node, and when it it supposed to be updated in the touchesBegan function, it never changes the rotation of the node).

It seems to me that I may just have a fundamental misunderstanding of how variables are delt with in Swift. I'm wondering if there is a way to update a variable that is declared early on in the Class file?

Is what i'm doing something that makes sense? Does anyone have an idea of how I can fix my situation? My code is very long and would not make sense to post all of it, so here are the important parts:

Here is where I declare the 'rotation' variable I'm trying to update and use later on.

class GameScene: SKScene {
    let rotation: Int = 188400

Here is where the 'rotation' variable is used in the didMoveToView function:

let rotate = SKAction.rotateToAngle(CGFloat(-188400), duration: NSTimeInterval(60000))
anchorNode.runAction(rotate)

Here is where I attempt to update the 'rotation' variable in the touchesBegan function:

 override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    /* Called when a touch begins */

    if rotation == 188400 {

        println("Setting rotation backwards")

        let rotation = -188400

    }else{

        println("Setting rotation forwards")
        let rotation = 188400
    }

Any help is greatly appreciated!

Upvotes: 0

Views: 2158

Answers (1)

matt
matt

Reputation: 535306

The problem is that when you say

    let rotation = -188400

You create a different rotation variable and set its value. You are not setting the instance variable (property) rotation. To do that, omit let:

    rotation = -188400

What I personally like to do is write self whenever referring to my instance variables. So I'd write your code like this:

if self.rotation == 188400 {
    println("Setting rotation backwards")
    self.rotation = -188400
}

And so on. That use of self is not required, but to me it sure clarifies where this variable comes from - and it looks like such clarification is exactly what you need here!

Also, as @danielbeard points out, you're not going to be able to update self.rotation unless you declare it with var, not let.

Upvotes: 2

Related Questions