是否可以访问swift 4中函数之外的函数中创建的变量

是否可以访问swift 4中函数之外的函数中创建的变量,swift,Swift,我需要访问在脚本前面创建的函数中创建的变量,但当我输入变量名时,它会显示使用未解析标识符。我一直在想办法解决这个问题,但什么也没想到。谢谢你的帮助 这是我在脚本前面创建的函数,我需要访问的变量是location.x override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { var location = t

我需要访问在脚本前面创建的函数中创建的变量,但当我输入变量名时,它会显示
使用未解析标识符
。我一直在想办法解决这个问题,但什么也没想到。谢谢你的帮助

这是我在脚本前面创建的函数,我需要访问的变量是
location.x

 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        var location = touch.location(in: self.view)
            
        _ = location.x
        location.x = location.x - 43
        
        Head.frame = CGRect(x: CGFloat(location.x), y: 451,width: Head.frame.size.width,height: Head.frame.size.height)

您可以尝试在类中保存变量:

var xLocation: Double // you may want to initialize it (or make optional)

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    ...
    self.xLocation = location.x
}

请添加一个。如果您不向我们显示您的代码,我们将无法帮助您。请将属性添加到您的类中,并在函数中进行设置。谢谢所有帮助我解决此问题的人。我现在几乎让它工作了,除了它现在说的事实——不能将“CGFloat”类型的值转换为预期的参数类型“ClosedRange”——休,这可能与你问题中的问题无关。你从哪里得到这个错误?如果eggOney==431&&xLocation==xLocation+0…86{}@Hugh,你不能只给一个数字加上一个范围。你想达到什么目的?@Hugh我建议你用你的新问题创建另一个帖子,并详细描述你的问题。我会尽力帮你:)
var xLocation: Double // you may want to initialize it (or make optional)

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    ...
    self.xLocation = location.x
}
if eggOney == 431 && location.x == self.xLocation + 0.86