Swift 如何引用函数中的变量?

Swift 如何引用函数中的变量?,swift,sprite-kit,Swift,Sprite Kit,如何从另一个函数(collide)调用我在函数(hello)中创建的sun对象 不能-sun变量是hello函数的局部变量,并且不存在于其范围之外 如果从hello调用了collide,则可以将其作为参数传递: func collide(sun: SKSpriteNode) { if (CGRectIntersectsRect(player.frame, sun.frame)) { [EndGame]; } } func hello() { let su

如何从另一个函数(collide)调用我在函数(hello)中创建的sun对象


不能-sun变量是
hello
函数的局部变量,并且不存在于其范围之外

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

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

func hello() {
    let sun = SKSpriteNode(imageNamed: "Sun")
    ...
    collide(sun)
}
否则,如我所想,如果这些是类的实例方法,只需将
sun
变量转换为实例属性:

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")
    }
}

不能-sun变量是
hello
函数的局部变量,并且不存在于其范围之外

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

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

func hello() {
    let sun = SKSpriteNode(imageNamed: "Sun")
    ...
    collide(sun)
}
否则,如我所想,如果这些是类的实例方法,只需将
sun
变量转换为实例属性:

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")
    }
}

除了Antonio的答案外,您还可以使用唯一的名称搜索
SKNode的子节点

比如说

let sun = SKSpriteNode(imageNamed:"Sun")
sun.name = "sun"
self.addChild(sun)
你可以在6点之前拿回来

if let sun =  self.childNodeWithName("sun")
{
    //use sun here
}

childNodeWithName
返回可选的
SKNode?

除了Antonio的答案外,您还可以使用唯一的名称搜索
SKNode的子节点

比如说

let sun = SKSpriteNode(imageNamed:"Sun")
sun.name = "sun"
self.addChild(sun)
你可以在6点之前拿回来

if let sun =  self.childNodeWithName("sun")
{
    //use sun here
}

childNodeWithName
返回一个可选的
SKNode?

因为
sun
变量只在
hello()
函数的作用域内,所以不能返回。您可能希望将
sun
变量设置为类变量将sun设置为类变量是否要从
hello
返回太阳精灵?如何将其设置为类变量@KaanDedeoglu@RayToal我尝试使用“hello”返回sun sprite,但后来我得到了一个“调用中参数“completion”的缺少参数”,因为
sun
变量仅在
hello()
函数的范围内。您可能希望将
sun
变量设置为类变量将sun设置为类变量是否要从
hello
返回太阳精灵?如何将其设置为类变量@KaanDedeoglu@RayToal我尝试使用“hello”返回太阳精灵,但后来我得到了“调用中缺少参数“completion”的参数”