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

6

我试图在一个函数中添加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)

    }


}
2个回答

18

确保方法出现在类的左右大括号之间

class A {

// 在这里定义一个方法

}

// 你可能已经在这里声明过它。


6

Nas,

要使用"self",函数需要作为一个类的一部分。

"self"指的是方法(或者在Swift中称之为“func”)被应用的当前实例。如果在全局级别定义一个函数,那么它不是类的一部分,因此无法与类的实例关联起来。

因此,在该情况下使用"self"是不可能的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接