gpt4 book ai didi

Swift 泛型,类型在运行时首先已知

转载 作者:搜寻专家 更新时间:2023-10-31 19:38:26 25 4
gpt4 key购买 nike

我有一个关于 swift 和泛型的问题。我尝试做的是获得一个具有泛型类型的对象。但是我首先在运行时知道类型。但要快速切入正题。

新编辑 block :

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

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

新编辑的 block 结束:

我有两个具有通用类型的类:

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

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

感谢您的帮助!

问候

阿图尔

最佳答案

let type = obj.getType

好的,所以 type 是一个 NSObject.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()
}

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

关于Swift 泛型,类型在运行时首先已知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34668689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com