SpringN
SpringN

Reputation: 954

Why can't I use self in a func Swift

I'm trying to self to add SKSpriteNodes to the view in a function, but Xcode will not allow me to do so. It gives me the error "Use of unresolved identifier 'self'"

 func indicate() {
if test == 0 {
    var large = ((CGFloat(largest)*54) - 29) - selectedNode.position.x
    var small = selectedNode.position.x - ((CGFloat(smallest)*54) - 29)

    indicatorRight.position = CGPointMake(selectedNode.position.x + large, selectedNode.position.y)
    indicatorRight.userInteractionEnabled = true
    indicatorRight.zPosition = 0.5

    indicatorLeft.position = CGPointMake(selectedNode.position.x - small, selectedNode.position.y)
    indicatorLeft.userInteractionEnabled = true
    indicatorLeft.zPosition = 0.5


    println(indicatorLeft.position)
    //  println(smallest)
    self.addChild(indicatorRight)
    self.addChild(indicatorLeft)

    }


}

Upvotes: 6

Views: 9660

Answers (2)

YSR fan
YSR fan

Reputation: 735

Make sure the method is presented in the Class open and closing braces

class A {

// You need to define a method here

}

// You might have declared it here.

Upvotes: 18

Jean Le Moignan
Jean Le Moignan

Reputation: 22236

Nas,

For a func to be able to use "self", it needs to be part of a class.

"self" refers to the current instance upon which a method (or in Swift parlance: "func") is applied. If a func is defined at global level, then if is not part of a class, therefore it cannot be associated with an instance of a class.

Hence the impossibility to use 'self" in that context.

Upvotes: 6

Related Questions