为什么我不能在函数Swift中使用self

Nas*_*296 6 swift

我正在尝试将SKSpriteNodes添加到函数中的视图中,但Xcode不允许我这样做.它给了我错误"使用未解析的标识符'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)

    }


}
Run Code Online (Sandbox Code Playgroud)

YSR*_*fan 18

确保方法在类打开和关闭括号中显示

A级{

//你需要在这里定义一个方法

}

//你可能在这里宣布了它.


Jea*_*nan 6

纳斯,

对于能够使用"self"的func,它需要成为类的一部分.

"self"指的是应用方法(或Swift用语:"func")的当前实例.如果在全局级别定义了func,那么if 不是类的一部分,因此它不能与类的实例相关联.

因此,在这种情况下不可能使用"自我".