Swift: 在 touchesBegan 中使用 switch 语句

Swift: Using switch statement in touchesBegan

我想在 SKScene 清理我的 touchesBegan(..)。我想做一个案例陈述而不是我的 if .. else 链。但是,我在实现时遇到错误,这表明我不知道底层是如何实现相等的。

代码前:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        if self.nodeAtPoint(location) === playLabel {
            buildLevelSelect()
        } else if self.nodeAtPoint(location) === aboutLabel {
            createAboutView()
        } else if self.nodeAtPoint(location) === storeLabel {
            createStore()
        }
    }
}

代码后:点击周围后,一些标签点击工作,但其他一些引发 Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode 0x0) 错误:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        switch(self.nodeAtPoint(location)){
        case playLabel :
            buildLevelSelect()
        case aboutLabel :
            createAboutView()
        case storeLabel :
            createStore()
        default : break
    }
}

如果您想要 === 行为,您可以编写一种看起来很奇怪但实用的 switch

switch(true){
        case self.nodeAtPoint(location) === playLabel : buildLevelSelect()
        case self.nodeAtPoint(location) === aboutLabel : createAboutView()
        case self.nodeAtPoint(location) === storeLabel : createStore()
        default : break
}

在我看来,这仍然比 if-else 链看起来更干净。

完成此操作的最简单方法是填充节点的 .name 属性,这样您就可以改用名称。那么您的开关将如下所示:

switch (self.nodeAtPoint(location).name ?? "") { 
    case "playLabel" :
        buildLevelSelect()
    case "aboutLabel" :
        ...

您也可以在 switch 语句中强制转换对象,然后您的代码会按预期工作

    if let touch = touches.first as UITouch! {

        let touchLocation = touch.location(in: self)

        switch self.atPoint(touchLocation) {
            case redBox as SKSpriteNode:
                print("touched redBox")
            case greenBox as SKSpriteNode:
                print("touched greenBox")
            default:
                print("touched nothing")
        }
    }