Я пытаюсь создать экземпляр класса с использованием строки и передать его значение. Это то, что я делаю сейчас:
var scene = Level1(size: self.size)
Мне нужно было бы что-то вроде этого:
var levelId = 1
var scene = imaginaryFunction("Level\(levelId)", self.size)
// scene should be an instance of Level1 class
levelId++
var scene2 = imaginaryFunction("Level\(levelId)", self.size)
// scene2 should be an instance of Level2 class
levelId += 8
var scene3 = imaginaryFunction("Level\(levelId)", self.size)
// scene3 should be an instance of class Level10
Вы можете попробовать следующее, но это может не дать никакого преимущества по сравнению со стандартом Swift и протоколами:
// This protocol defines the common initializer for all Level classes
protocol MyLevelProtocol {
init (size : Int)
}
@objc(Level1) // This defines the ObjC name of the class. Needed for NSClassFromString
class Level1 : MyLevelProtocol {
required init (size : Int) {
// Do your init
}
}
@objc(Level2)
class Level2 : MyLevelProtocol {
required init (size : Int) {
// Do your init
}
}
func getLevelFromString(levelName : String, size : Int) -> AnyObject? {
if let levelClass = NSClassFromString(levelName) as? MyLevelProtocol.Type {
return levelClass.init(size: size) as? AnyObject
} else {
// Level not found
return nil
}
}
let scene1 = getLevelFromString("Level1", size: 1)
let scene2 = getLevelFromString("Level2", size: 4)
AnyObject
? Вы должны просто оставить его как MyLevelProtocol
Level1
,Level2
иLevel3
, и я хочу , чтобы назначить экземпляр одного из этих классов наvar scene
, но я хочу , чтобы определить , какие из этих 3 -х классов , чтобы выбрать с помощью строки.