使用字符串创建类实例

时间:2015-07-27 21:22:41

标签: ios string swift class instance

我正在尝试使用字符串创建类的实例,并将值传递给它。这是我目前的做法:

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

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法,但它可能不会提供优于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)