Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift2 如何通过字符串获取类类型,然后在强制转换中使用它?_Swift2_Xcode7 - Fatal编程技术网

Swift2 如何通过字符串获取类类型,然后在强制转换中使用它?

Swift2 如何通过字符串获取类类型,然后在强制转换中使用它?,swift2,xcode7,Swift2,Xcode7,我试图用一个通过强制转换返回子类的特定方法实例化一个对象。我只能通过名称(字符串)传递类类型。但是编译器抱怨它不是一个类型 guard let entityClass = NSClassFromString(entity.rawValue) else { preconditionedFailure("Cannot find entity with name \(entity.rawValue)") } let obj = NSEntityDescription.insertNewObje

我试图用一个通过强制转换返回子类的特定方法实例化一个对象。我只能通过名称(字符串)传递类类型。但是编译器抱怨它不是一个类型

guard let entityClass = NSClassFromString(entity.rawValue) else {
    preconditionedFailure("Cannot find entity with name \(entity.rawValue)")
}
let obj = NSEntityDescription.insertNewObjectForEntityForName(entity.rawValue, inManagedObjectContext: moc) as? entityClass
编译器抱怨entityClass不是类型。我知道这是一个可选的,但即使我打开它!即使NSClassFromString返回可选(AnyClass),编译器仍然不将其视为类型

编辑:我在另一个线程中找不到真正的解决方案。编译器在转换时出错显示:

let obj = NSEntityDescription.insertNewObjectForEntityForName(entity.rawValue, inManagedObjectContext: moc) as? entityClass
“entityClass不是类型。”


那么,有人能解释为什么即使entityClass实际上是可选的(AnyClass),强制转换也不起作用吗?

我认为可能的副本不起作用,因为编译器需要一个文本类型名。您所尝试的类似于
var obj:entityClass
,它也会因语法错误而失败。如果你没有尝试投射就得到了你的物体,你有什么问题?