我想将这些子类的实例存储在一个数组中,这样它们就可以迭代并以相同的方式处理所有这些子类,但显然,没有办法将子类转换为泛型超类.
以下是一些说明问题的代码(您可以将其复制粘贴到 *** 场中以查看结果):
// Lets create regular classesclass Fruit { var text: String { return "I am some Fruit" }}class Apple: Fruit { overrIDe var text: String { return "I am an Apple" }}class Orange: Fruit { overrIDe var text: String { return "I am an Orange" }}// This obvIoUsly works:let test1: Fruit = Apple()let test2: Fruit = Orange()// Let's create some generic classclass Tree<T: Fruit> { let fruit: T init(fruit: T) { self.fruit = fruit }}// Subclasses from the generic class (these work)class AppleTree: Tree<Apple> { convenIEnce init() { self.init(fruit: Apple()) }}class OrangeTree: Tree<Orange> { convenIEnce init() { self.init(fruit: Orange()) }}// This works:let tree: Tree<Fruit> = Tree(fruit: Apple())tree.fruit.text // "I am an Apple"// This works:let appleTree1: Tree<Apple> = AppleTree()appleTree1.fruit.text // "I am an Apple"// This fails: "Cannot convert value of type 'AppleTree' to specifIEd type 'Tree<Fruit>'let appleTree2: Tree<Fruit> = AppleTree()// This works:let fruitArray: [Fruit] = [Apple(),Orange()]// THIS IS MY GOAL:// This fails: "Cannot convert value of type 'AppleTree' to specifIEd type 'Tree<Fruit>'let treeArray: [Tree<Fruit>] = [AppleTree(),OrangeTree()]// Let's try with a generic subclassclass FruitTree<T: Fruit>: Tree<T>{}// This works:let genericTree: Tree<Fruit> = FruitTree(fruit: Apple())// Let's try with a generic but more concrete subclassclass GenericOrangeTree<T: Orange>: Tree<T>{ convenIEnce init() { self.init(fruit: Orange() as! T) }}// This works:let genericOrangeTree1 = GenericOrangeTree(fruit: Orange())let genericOrangeTree2 = GenericOrangeTree()// This fails: Cannot invoke initializer for type 'GenericOrangeTree<Orange>' with an argument List of type '(fruit: Orange)'let genericTree2: Tree<Fruit> = GenericOrangeTree(fruit: Orange())// Again,this fails: "Cannot convert value of type 'GenericOrangeTree<Orange>' to specifIEd type 'Tree<Fruit>'let genericTreeArray: [Tree<Fruit>] = [GenericOrangeTree()]
我试图做的是通过treeArray变量在示例代码中说明的.
我不明白为什么代码失败时会失败.我的直觉说这应该有效,我无法找到解决这个问题的方法.
TL; DR:我有一个带有一些子类的Generic类,我想要一个填充了子类的Generic类的数组,但编译器抱怨.
解决方法 您正在混淆Generics实现之前和之后的类型层次结构.使用泛型类/ func,您基本上可以设置一个在编译时解析的模板(编译器宏).如果你说
Generic<SubClass1>Generic<SuperClass>
这些由编译器解析为类型:
class Generic_SubClass1 { let property : SubClass1}class Generic_SuperClass { let property : SuperClass}
在解析泛型之后,这两种类型不共享基本类型,因此不能相互转换.它们是完全分开的.
不确定也没试过,但也许这就是你想要的:
class GenericBase { let property : SuperClass}class Generic<T: SuperClass> : GenericBase { final var typedProperty : T { get { return property as T } set { property = T } }}
然后,您可以使用GenericBase作为公共祖先,并使用动态类型来检查子类.
P.S.:您的代码有点难以理解,可能使用类似’Fruit’,’Apple’和’Orange’的东西 – 比’Superclass’,’Subclass1′,’Subclass2’更容易阅读;-)
总结以上是内存溢出为你收集整理的arrays – Swift – 如何存储在泛型类型的Array子类中全部内容,希望文章能够帮你解决arrays – Swift – 如何存储在泛型类型的Array子类中所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)