问题
I have a game in Swift where each of my levels is a separate class inherited from the base GameScene class (it's a lot easier this way for what I'm doing, don't judge me). I also have a menu which has a button for each level. This is how the buttons loads the level:
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))
}
}
}
To me, this switch looks incredibly ugly and pointless, but I can't think of a way to avoid it. I was hoping someone here could help me out with this, I just can't think of a better alternative.
回答1:
You could construct your Level's class name as a string "Level\(name)"
first and then get the actual class you need by passing it's name to the function:
func classFromString(_ className: String) -> AnyClass! {
let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!
return cls
}
Usage example:
let className = "Level1"
let levelInstance = (classFromString(className) as! GameScene).init(size: frame.size)
... but of course the best advice would be to avoid such kind of architecture
回答2:
You can do this instead:
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]
}
来源:https://stackoverflow.com/questions/44426024/swift-simplify-menu-button-logic