我想在 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/