关于swift:如何在函数中引用变量?

How do I refer to a variable in a function?

如何从另一个函数(碰撞)中调用在函数(hello)中创建的太阳对象?

1
2
3
4
5
6
7
8
func collide() {
        if (CGRectIntersectsRect(player.frame, **sun.frame**)) {
            [EndGame];
        }

 func hello() {
        let sun = SKSpriteNode(imageNamed:"Sun")
}


您不能-sun变量是hello函数的局部变量,并且在其作用域之外不存在。

如果从hello调用collide,则可以将其作为参数传递:

1
2
3
4
5
6
7
8
9
10
11
func collide(sun: SKSpriteNode) {
    if (CGRectIntersectsRect(player.frame, sun.frame)) {
        [EndGame];
    }
}

func hello() {
    let sun = SKSpriteNode(imageNamed:"Sun")
    ...
    collide(sun)
}

否则,如果我认为这些是类的实例方法,只需将sun变量转换为实例属性:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Test {
    private var sun: SKSpriteNode?

    func collide(sun: SKSpriteNode) {
        if let sun = self.sun {
            if (CGRectIntersectsRect(player.frame, sun.frame)) {
                [EndGame];
            }
        }
    }

    func hello() {
        self.sun = SKSpriteNode(imageNamed:"Sun")
    }
}

除了安东尼奥的答案外,您还可以使用唯一的名称搜索SKNode's children

例如。

1
2
3
let sun = SKSpriteNode(imageNamed:"Sun")
sun.name ="sun"
self.addChild(sun)

您可以通过

找回它

1
2
3
4
if let sun =  self.childNodeWithName("sun")
{
    //use sun here
}

childNodeWithName返回可选的SKNode?