Swift 2:类型的值&#39;设置<uitouch>&#39;没有会员&#39; anyObject&#39;

时间:2015-12-19 18:08:05

标签: swift sprite-kit swift2 skspritenode uitouch

我检查了我的旧游戏,我想在Swift 2.0中更新它。当我试图修复它时,Xcode发现了一个错误。错误是类型的值&#39;设置&#39;在这行代码中没有成员&#39; anyObject&#39;

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

功能

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))
}

那么在这里要解决什么?

1 个答案:

答案 0 :(得分:8)

鉴于Set UITouch定义如下

touches: Set<UITouch>

您可以使用此代码检索触摸

let touch = touches.first

泛型

无需强制将检索到的元素强制转换为UITouch。事实上,现在用Objective-C编写的Apple API已经使用泛型进行了更新。这意味着,在这种情况下,您会收到Set UITouch Set NSObject SetUITouch字面上可能包含任何对象)。 因此,first 已经知道所包含的元素为Optional

选配

Set计算的属性确实返回nil。事实上,如果guard let touch = touches.first else { debugPrint("Ops, no touch found...") return } // here you can use touch 为空,则会返回<input type="number" id="floatOne" required>

打开元素的好方法是

<script>
function calcExactFloat(){
    var floats = new Array(document.getElementById("floatOne").value, document.getElementById("floatTwo").value,document.getElementById("floatThree").value,document.getElementById("floatFour").value,document.getElementById("floatFive").value,document.getElementById("floatSix").value,document.getElementById("floatSeven").value,document.getElementById("floatEight").value,document.getElementById("floatNine").value,document.getElementById("floatTen").value);

    var sum = 0;

    for(var i = 0; i < floats.length; ++i){
        sum = sum + floats[i];
        console.log(sum);
    }