如何使用AnyClass对象中定义的类型在Swift中声明变量? [英] How can I declare a variable in Swift using the type defined in an AnyClass object?

查看:226
本文介绍了如何使用AnyClass对象中定义的类型在Swift中声明变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my old Obj-C code I could declare a dictionary whose values were the Class types of other classes

NSMutableDictionary *Methods = [[NSMutableDictionary alloc] init];
[Methods setObject:[AuthReturnValue class] forKey:@"Authenticate"];
[Methods setObject:[MyOptions class] forKey:@"GetOptions"];

稍后,根据键,我可以将Class分配给另一个变量

Later, based off of the key, I could assign that Class to another variable

(在标题中)

Class returnType;

(在实现中):

returnType = (Class)[Methods objectForKey:methodName];

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

And then I could use this Class variable to declare a new variable of that same type (in this case it's using JSONModel and initializing it with an NSDictionary from elsewhere)

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

这很好并且方便,并且因为JSONModel实现了initWithDictionary,这意味着我可以以这种方式引入Class,而不必实例化特定类型.

This was nice and convenient and since JSONModel implements initWithDictionary, meant that I could just pull in the Class in this way without having to instantiate a particular type.

我不知道如何在Swift中做到这一点.

I can't figure out how to do this in Swift.

例如,这不起作用:

var result: self.returnType.self()
var result: AnyClass = self.returnType.self

和几十个变体.

如何在Swift中将变量声明为AnyClass对象中定义的class?还是我要把这都弄错了?

How can I declare a variable in Swift to be the class defined in an AnyClass object? Or am I going about this all wrong?

推荐答案

据我所知,您无法实例化AnyClass.您必须将其转换为更具体的类型.此外,要使用其元类型实例化的类型必须具有必需的初始化程序.如果我理解您的示例,则AuthReturnValueMyOptions都是JSONModel的子类,它们都有init(responseObject:error:)初始化程序.然后,每个子类都必须要求并实现该初始化程序.

You can't instantiate AnyClass, as far as I know. You must downcast it to a more concrete type. Additionally, the type you want to instantiate with its metatype, must have a required initialiser. If I understood your example, AuthReturnValue and MyOptions are both subclasses of JSONModel, which has init(responseObject:error:) initialiser. Then that initialiser must be required and implemented by every subclass.

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)
    }
}

现在您可以执行以下操作:

Now you can do something like this:

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)
}


更新:

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

The above code works well with native Swift classes, but crashes currently (Xcode6-Beta6) if used with subclasses of Objective-C classes. The workaround is to store metatype values in a [String : Any.Type] dictionary and downcast before using. The following example shows how to do this with a subclass of 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))
}

这篇关于如何使用AnyClass对象中定义的类型在Swift中声明变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆