Tuesday, April 28, 2015

iOS touch events with Swift version 1.2

Prior to the 1.2 version of Swift, the touchesBegan(), touchesMoved() and touchesEnd() methods used the NSSet type to store the collection of UITouch instances that represent the touches.  In version 1.2 of Swift, Apple introduced the new native Set type and replaced the NSSet type in the touchesBegan(), touchesMoved() and touchesEnd() methods with this new Set type.  With this change we can no longer access the UITouch instances in the same way that we did prior to version 1.2.

Touch events prior to version 1.2
Prior to version 1.2 of Swift, I used the following code to access a single UITouch instances from the NSSet collection.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent)  {
   if let touch = touches.anyObject() {
       lastPoint = touch. locationInView(self)

   }
}

This will now throw the following error:

Overriding method with selector 'touchesBegan:withEvent:' has incompatible type '(NSSet, UIEvent) -> ()'

Touch events starting with version 1.2
The following code demonstrates how we would want to access a single UITouch event with version 1.2 of Swift.

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    if let touch = touches.first as? UITouch {
        lastPoint = touch.locationInView(self)
    }
}

If we wanted to cycle though all of the touch events we would use the following code:

for touch in touches  {
    var myTouch = touch as? UITouch
    //code here 
}


While this change did take people by surprise; the overall addition of the Set type out weights the headache of these changes.  If you want to read more about the new Set type, see my blog post here: http://masteringswift.blogspot.com/2015/04/swift-native-set-type.html

No comments:

Post a Comment