我正在制作一款包含很多关卡的 Swift 游戏。每个级别都在一个具有顺序名称的文件中:
Level1.swift
Level2.swift
Level3.swift
...
每个文件中都有一个类,类名与文件名相同。
一切都是类的原因是因为所有类都共享来自基类的相似功能,还因为有很多共享变量。
问题是,我不知道如何只使用整数来加载关卡而不会造成这种灾难:
switch Int(level)! {
case 1:
newScene = Level1(size: frame.size)
case 2:
newScene = Level2(size: frame.size)
case 3:
newScene = Level3(size: frame.size)
...
我不能使用 SKScene(fileNamed:)
因为我没有任何 .sks 文件,只有实际的类。如果我可以像使用音频文件一样简单地加载一个场景——通过使用 Bundle.main.url——那就太好了,但这是不可能的。我尝试使用带有默认行为扩展的协议(protocol),但我仍然想不出一种很好地加载它的方法。任何帮助将不胜感激。
最佳答案
我认为您的“灾难性”解决方案确实提供了 Swift 中最简洁、类型检查的解决方案。如果您想基于仅在运行时已知的名称初始化一个类,您必须冒险进入 ObjC 领域:
首先,让基类继承自NSObject
(如果还没有的话):
class Level : NSObject {
var levelId: Int = 0
required init(size: NSSize) { }
// all other common stuffs here
}
class Level1 : Level {
required init(size: NSSize) {
super.init(size: size)
self.levelId = 1
// ...
}
}
class Level2 : Level {
required init(size: NSSize) {
super.init(size: size)
self.levelId = 2
// ...
}
}
class Level3 : Level {
required init(size: NSSize) {
super.init(size: size)
self.levelId = 3
// ...
}
}
使用方法如下:
let levelId = 2
// Module Name = Product Name from your Build Settings, unless you put
// the Level classes into sub-namespace
let className = "ModuleName.Level\(levelId)"
let LevelClass = NSClassFromString(className) as! Level.Type
// At build time, the compiler sees this as an object of type Level,
// but it's actually a Level2 object. You can cast it to Level2 if
// you need to do something specific to that level.
let level = LevelClass.init(size: frame.size)
关于ios - Swift:按整数加载级别类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44510827/