Swift:简化菜单按钮逻辑

时间:2017-06-08 03:13:25

标签: ios swift switch-statement

我在Swift玩了一个游戏,我的每个级别都是从GameScene基础类继承而来的一个单独的类(对于我正在做的事情,这样做很容易,不要判断我)。 我还有一个菜单,每个级别都有一个按钮。这是按钮加载级别的方式:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  if let t = touches.first {
    let node = atPoint(t.location(in: self))
    if let name = node.name {
      let newScene: GameScene!
      switch Int(name)! {
      case 1:
        newScene = Level1(size: frame.size)
      case 2:
        newScene = Level2(size: frame.size)
      case 3:
        newScene = Level3(size: frame.size)
      case 4:
        newScene = Level4(size: frame.size)
      case 5:
        newScene = Level5(size: frame.size)
      case 6:
        newScene = Level6(size: frame.size)
      case 7:
        newScene = Level7(size: frame.size)
      default:
        newScene = Level1(size: frame.size)
      }
      view?.presentScene(newScene, transition: .crossFade(withDuration: 0.5))
    }
  }
}

对我来说,这个开关看起来非常丑陋和毫无意义,但我无法想到避免它的方法。我希望有人可以帮助我解决这个问题,我只是想不出更好的选择。

2 个答案:

答案 0 :(得分:1)

您可以首先将Level的类名构造为字符串"Level\(name)",然后通过将其名称传递给函数来获取所需的实际类:

func classFromString(_ className: String) -> AnyClass! {
    let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
    let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!
    return cls
}

用法示例:

let className = "Level1"
let levelInstance = (classFromString(className) as! GameScene).init(size: frame.size)

......但当然最好的建议是避免这种架构

答案 1 :(得分:-1)

您可以这样做:

    var newScene: GameScene!

    //Level1 is repeating on 0 and 1'st index

    let arrScene : [GameScene] = [Level1(size: frame.size),Level1(size: frame.size),Level2(size: frame.size),Level3(size: frame.size),Level4(size: frame.size),Level5(size: frame.size),Level6(size: frame.size),Level7(size: frame.size)]

    if Int(name)! <=7 && Int(name)! > 0{

    newScene  = arrScene[Int(name)!]

    }else{

    //Default level1 
    newScene  = arrScene[0]

    }