Swift Generic,在运行时首先知道类型

时间:2016-01-08 02:48:24

标签: swift generics runtime

我有一个关于swift和泛型的问题。我尝试做的是获取具有泛型类型的Object。但我首先在运行时知道类型。但要快速达到目的。

新编辑的区块:

也许我可以用班级名字来做?我有一个类名作为字符串。我通过镜子得到它。我可以在字符串中创建具有该类名的通用实例吗?

let classname: String = "ClassA"
let firstA: a<classname> = a<classname>()
//            ^^^^^^^^^      ^^^^^^^^^
//            what to put here???          

新修改的版块结束:

我有两个泛型类型的类:

这是我的类型必须实现的协议:

protocol ToImplement {
    func getTypeForKey(key: String) -> NSObject.Type
}

这是我用于第一个通用类型的类:

class MyClass: ToImplement {
    func getTypeForKey(key: String) -> NSObject.Type {
        if key == "key1" {
            return UIView.self
        } 
        else {
            return UIButton.self
        }
    }
}

这是我的第一个具有泛型类型的类:

class a<T:ToImplement> {
    func doSomethingWith(obj: T) -> T {

        // the next part usually runs in an iteration and there can be
        // a lot of different types from the getTypeForKey and the number
        // of types is not known

        let type = obj.getTypeForKey("key1")
        let newA: a<type> = a<type>()       // how could I do this? To create a type I do not know at the moment because it is a return value of the Object obj?
        //          ^^^^      ^^^^
        //          what to put here???


        return obj
    }
}

这就是我如何使用它:

let mycls: MyClass = MyClass()
let firstA: a<MyClass> = a<MyClass>()
firstA.doSomethingWith(mycls)

现在我的问题是:我可以使用泛型类型创建一个类a的实例作为函数的返回值吗?这甚至可能吗?

如果无法做到这一点,我怎么能用其他实例创建一个泛型类型的实例。类似的东西:

let someA: a<instance.type> = a<instance.type>()

感谢您的帮助!

问候

阿图尔

1 个答案:

答案 0 :(得分:1)

let type = obj.getType

好的,typeNSObject.Type。由于NSObject提供init(),您可以使用

实例化此类型
let obj = type.init()  // obj is a NSObject (or subclass)
return obj

当然,如果getType()返回的实际类型没有实现init(),这将在运行时失败。

另一种选择是使用相关的类型:

protocol ToImplement {
    typealias ObjType: NSObject
}

然后你可以将它用作通用约束:

func makeAnObject<T: ToImplement>(obj: T) -> T.ObjType {
    return T.ObjType()
}

这给出了基本相同的结果。

相关问题