在两个函数之间传递变量

Passing Variables Between Two Functions

相关代码如下:

func touchLocationAngle() {
        func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            for touch in touches{
                var touchLocation = touch.location(in: self)
                var angle1 = atan2(1SpriteNode.position.y - touchLocation.y , 1SpriteNode.position.x - touchLocation.x)
                var angle = angle1 - CGFloat(Double.pi / 1)
            }
        }
    }

    func moveToTouchLocation() {

    }

我想从第一个函数中获取角度变量并在第二个函数中使用。我不想使变量成为全局变量。我看过 google 和 youtube,但每当我使用他们的代码时,它都会显示错误。

一些事情,我可以根据需要编辑我的答案,但是第一个函数的 objective 是什么?据我所知,它是一个功能,包含另一个功能,通过触摸。但我也注意到 angle 也会在每个循环周期被覆盖,只留下最后一次触摸的角度。我的回答是我认为你想要的,但如果不是,请澄清。

您需要 return 第一个函数中的角度,目前第一个函数没有 return 值。然后你会想要调用第一个函数,并将值传递给第二个,例如,像这样

func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
        var touchLocation = touch.location(in: self)
        var angle1 = atan2(1SpriteNode.position.y - touchLocation.y , 1SpriteNode.position.x - touchLocation.x)
        var angle = angle1 - CGFloat(Double.pi / 1)
        moveToTouchLocation(angle)
    }
}

func moveToTouchLocation(angle: CGFloat) {
    // whatever you want to do here.
}