Swift - 从函数中返回的类型实例化类

时间:2016-03-23 09:34:47

标签: swift

是否可以从函数返回类的类型?

我正在尝试做这样的事情:

func giveMeAClass() -> AnyClass {
    return String.self
}

let theClass = giveMeAClass()

let instantiatedFromTheClass = theClass()

let castedFromTheClass = someObject as! theClass

编辑:

我正在尝试做一些更有用的事情的另一个例子

class BaseModel {
    var baseProperty: String!
}

class TextModel: BaseModel {
    var textProperty: String!
}

class DateModel: BaseModel {
    var dateProperty: NSDate!
}

class BaseCell<T: BaseModel>: UITableViewCell {
    var model: T!
}

class TextCell: BaseCell<TextModel> {

}

class DateCell: BaseCell<DateModel> {

}

func getCellTypeForModel(model: BaseModel) -> ??? {

    if model is TextModel {
        return TextCell.Type // ???
    }

    else if model is DateModel {
        return DateCell.self // ???
    }

    return BaseCell.somethingElse // ???
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let model = cellModels[indexPath.item] as! BaseModel
    let cellType = getCellTypeForModel(anyModel)
    let castedCell = tableView.dequeueReusableCellWithIdentifier("identifier", forIndexPath: indexPath) as! cellType

    // give the model to the cell, customize it, etc

    return castedCell
}

1 个答案:

答案 0 :(得分:2)

从元类型初始化时,您需要显式调用initializer。 E.g。

protocol SimplyInitializable { init() }

extension String: SimplyInitializable {}
extension Int: SimplyInitializable {}

class Foo : SimplyInitializable {
    let foo : Int
    required init() { foo = 42 }
}

func getType<T: SimplyInitializable>(type: T.Type) -> SimplyInitializable.Type {
    return type
}

/* example usage */
var MyType = getType(String)
let foo = MyType.init() as! String // "", String

MyType = getType(Int)
let bar = MyType.init() as! Int // 0, Int

MyType = getType(Foo)
let baz = MyType.init() as! Foo
baz.foo // 42

请注意,您无需进行元类型分配的功能,例如

let MyType2 : SimplyInitializable.Type = Foo.self
let foobar = MyType2.init()