Swift 2: A value of type 'Set <UITouch>' does not have anyObject '

I checked my old game and I want to update it in Swift 2.0. When I tried to fix this, Xcode detected an error. Error A value of type 'Set' does not have anyObject 'element in this line of code:

var touch:UITouch = touches.anyObject() as! UITouch 

function:

 override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { self.runAction(SKAction.playSoundFileNamed("torpedo.mp3", waitForCompletion: false)) var touch:UITouch = touches.anyObject() as! UITouch //<-- Here is Error var location:CGPoint = touch.locationInNode(self) var torpedo:SKSpriteNode = SKSpriteNode(imageNamed: "torpedo") torpedo.position = player.position torpedo.physicsBody = SKPhysicsBody(circleOfRadius: torpedo.size.width/2) torpedo.physicsBody!.dynamic = true torpedo.physicsBody!.categoryBitMask = photonTorpedoCategory torpedo.physicsBody!.contactTestBitMask = alienCategory torpedo.physicsBody!.collisionBitMask = 0 torpedo.physicsBody!.usesPreciseCollisionDetection = true var offset:CGPoint = vecSub(location, b: torpedo.position) if (offset.y < 0){ return self.addChild(torpedo) var direction:CGPoint = vecNormalize(offset) var shotLength:CGPoint = vecMult(direction, b: 1000) var finalDestination:CGPoint = vecAdd(shotLength, b: torpedo.position) let velocity = 568/1 let moveDuration:Float = Float(self.size.width) / Float(velocity) var actionArray:NSMutableArray = NSMutableArray() actionArray.addObject(SKAction.moveTo(finalDestination, duration: NSTimeInterval(moveDuration))) actionArray.addObject(SKAction.removeFromParent()) torpedo.runAction(SKAction.sequence(actionArray)) } 

So what is the fix here?

+7
swift swift2 sprite-kit uitouch skspritenode
source share
1 answer

Given the Set of UITouch , defined as follows:

 touches: Set<UITouch> 

you can get a touch on this code

 let touch = touches.first 

Generics

There is no need to force the received item into UITouch . Infact now the Apple APIs written in Objective-C have been updated using generics. This means that in this case you get Set UITouch (not Set of NSObject , which could literally contain any object). Thus, Set already knows the contained UITouch elements.

Optionals

The computed property first returns Optional . Infact, if Set empty, it returns nil .

Good and safe element deployment technique

 guard let touch = touches.first else { debugPrint("Ops, no touch found...") return } // here you can use touch 
+8
source share

All Articles