Leem.fin Leem.fin - 1 year ago 74
Swift Question

local variable update itself , why

I created a

component (in main storyboard it occupies the whole screen). The class it linked to is called
which looks like this:

import UIKit

class MyFullView: UIView {
var myTouch: UITouch?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
// I only initialized myTouch here.
myTouch = UITouch()
myTouch = touches.first

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
// I just print out myTouch location, magically the value is updated for each finger movement, why?
print("myTouch = \(myTouch?.location(in: self))")
super.touchesMoved(touches, with: event)

I declared the variable
& initialized it in
callback. I don't have any code update the value of

But when I run my app in emulator, mouse click & move/drag, I can see the log .e.g.:

myTouch = Optional((100.5, 117.0))
myTouch = Optional((99.5, 117.0))
myTouch = Optional((99.0, 117.0))
myTouch = Optional((98.5, 117.0))
myTouch = Optional((98.5, 118.0))
myTouch = Optional((98.0, 118.0))
myTouch = Optional((97.5, 118.0))

Why & How the hell does
variable update the value of itself? I don't understand, could someone please explain to me what is the magic?

Answer Source

Your answer lies in the second line here:

        myTouch = UITouch()
        myTouch = touches.first

You have assigned myTouch to the first object in touches. When you get touch events, it happens that the UITouch will be the same instance for the lifecycle of the touch (until you get a finished or cancelled).

So you're seeing the positional updates of the touch in touchesMoved.

If you want to have the original location, you will need to store it then.

Note your code will have issues with multi touch.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download