ios - Swift:在 touchesBegan 中使用 switch 语句

标签 ios swift sprite-kit switch-statement skscene

我想在 SKScene 中清理我的 touchesBegan(..)。我想做一个 case 语句而不是我的 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 链看起来更干净。

关于ios - Swift:在 touchesBegan 中使用 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42585157/

相关文章:

ios - UITableView 延迟加载的图像在手指关闭之前不会加载

ios - Xamarin Forms 错误 - 'You MUST call Xamarin.Forms.Init(); prior to using it' - 仅限 TestFlight (iOS)

ios - UIScrollView 垂直滚动 + 自动布局

ios - 在 Sprite Kit 中设置类变量的问题

swift - 如何检测快速移动的分数节点

ios - 当应用程序进入后台时停止/启动 NSTimer

xml - xcode, iOS, XML文档解析

ios - 我的应用程序在 xcode 中崩溃,但没有此异常的堆栈跟踪

ios - 带有 xib 的自定义 UIView 中的 UIImageView 导出 nil

SwiftUI 验证文本字段中的输入