Hugh
Hugh

Reputation: 53

Is it possible to access a variable created in a function, outside of that function in swift 4

I need to access a variable created inside a function I have made earlier in the script, but when I enter the variable name, it says use of unresolved identifier. I have been trying to figure out ways to fix this problem but nothing comes to mind. Thanks for your help.

Here is the function I created earlier in the script, and the variable I need to access is 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)

And here is where I need to put location.x later in the code.

if eggOney == 431 && location.x == location.x + 0...86   

Upvotes: 2

Views: 55

Answers (1)

pawello2222
pawello2222

Reputation: 54516

You may try to save the variable in your class:

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
}

and later you can access it:

if eggOney == 431 && location.x == self.xLocation + 0.86

Upvotes: 1

Related Questions