简体   繁体   中英

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)

    }


}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM