我检查了我的旧游戏,我想在Swift 2.0中更新它.当我试图修复它时,Xcode发现了一个错误.错误是类型'Set'的值在此代码行中没有成员'anyObject':
var touch:UITouch = touches.anyObject() as! UITouch
功能:
override func touchesEnded(touches: Set, 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)) }
那么这里要解决什么?
鉴于Set
如下UITouch
定义
touches: Set
您可以使用此代码检索触摸
let touch = touches.first
无需强制将检索到的元素强制转换为UITouch
.事实上,现在用Objective-C编写的Apple API已经使用泛型进行了更新.这意味着,在这种情况下,您会收到Set
的UITouch
(不是Set
的NSObject
,可以从字面上包含任何对象).所以Set
已经知道所包含的元素是UITouch
.
将first
计算出的属性不会返回Optional
.事实上,如果它Set
是空的,它确实返回nil
.
解开元素的一种安全的好方法是
guard let touch = touches.first else { debugPrint("Ops, no touch found...") return } // here you can use touch