如何使用AnyClass对象中定义的类型在Swift中声明变量?

Tom*_*idd 1 objective-c type-conversion jsonmodel swift

在我的旧Obj-C代码中,我可以声明一个字典,其值是Class其他类的类型

NSMutableDictionary *Methods = [[NSMutableDictionary alloc] init];
[Methods setObject:[AuthReturnValue class] forKey:@"Authenticate"];
[Methods setObject:[MyOptions class] forKey:@"GetOptions"];
Run Code Online (Sandbox Code Playgroud)

之后,基于密钥,我可以将其分配Class给另一个变量

(在标题中)

Class returnType;
Run Code Online (Sandbox Code Playgroud)

(在实施中):

returnType = (Class)[Methods objectForKey:methodName];
Run Code Online (Sandbox Code Playgroud)

然后我可以使用这个Class变量声明一个相同类型的新变量(在这种情况下,它使用JSONModel并使用NSDictionary其他地方初始化它)

id<NSObject> result;
result = [[returnType alloc] initWithDictionary:(NSDictionary *)responseObject error:NULL];
Run Code Online (Sandbox Code Playgroud)

这很好,很方便,因为JSONModel实现了initWithDictionary,这意味着我可以通过Class这种方式拉入,而无需实例化特定类型.

我无法弄清楚如何在Swift中做到这一点.

例如,这不起作用:

var result: self.returnType.self()
var result: AnyClass = self.returnType.self
Run Code Online (Sandbox Code Playgroud)

还有几十个变种.

如何将Swift中的变量声明为对象中的class定义AnyClass?或者我这样做是错的?

Ivi*_* M. 5

AnyClass据我所知,你无法实例化.你必须将它转变为更具体的类型.此外,要使用其元类型实例化的类型必须具有必需的初始化.如果我理解你的例子,AuthReturnValue并且MyOptions都是JSONModel具有init(responseObject:error:)初始化的子类.然后必须由每个子类需要并实现该初始化器.

class JSONModel {
    required init(responseObject: NSDictionary, error: NSError?) {

    }
}

class AuthReturnValue : JSONModel {
    required init(responseObject: NSDictionary, error: NSError?) {
        super.init(responseObject: responseObject, error: error)
    }
}

class MyOptions : JSONModel {
    required init(responseObject: NSDictionary, error: NSError?) {
        super.init(responseObject: responseObject, error: error)
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

var methods = [String : JSONModel.Type]()
methods["Authenticate"] = AuthReturnValue.self
methods["GetOptions"] = MyOptions.self
if let returnType = methods["Authenticate"] {
    let result = returnType(responseObject: NSDictionary(), error: nil)
}
Run Code Online (Sandbox Code Playgroud)

更新:

上面的代码适用于本机Swift类,但如果与Objective-C类的子类一起使用,则会崩溃(Xcode6-Beta6).解决方法是[String : Any.Type]在使用之前将元类型值存储在字典中并向下转换.以下示例显示如何使用子类来执行此操作NSOperation.

class SomeOperation : NSOperation {

}

var dictionary = [String : Any.Type]()
dictionary["some operation"] = SomeOperation.self

if let aClass = dictionary["some operation"] as? NSOperation.Type {
    // Any initializer available in the superclass can be used for
    // creating instances. The compiler will not perform any checks,
    // as it does with native Swift classes, so we must ensure that subclasses
    // actually implement those initializers, either by automatically inheriting
    // or overriding.
    let test = aClass() 
    println(NSStringFromClass(test.dynamicType))
}
Run Code Online (Sandbox Code Playgroud)