简体   繁体   English

我可以在Realm Swift中使用异构集合吗?

[英]Can I have a heterogeneous collection in Realm Swift?

I would like to have an object that is an ordered collection of multiple different kinds of Realm Objects, like so... 我想要一个对象,它是多种不同领域对象的有序集合,就像这样……

public class One: Object {
    dynamic var name = ""
}

public class Two: Object {
    dynamic var label = ""
}

public class Listing: Object {
    let onesAndTwos = List<Object>()
}

Is there an elegant way to do this? 有没有一种优雅的方法可以做到这一点?

I know I can add an Enum-like wrapper object... 我知道我可以添加一个类似枚举的包装对象...

public class OneOrTwo: Object {
    dynamic var one: One?
    dynamic var two: Two?
}

public class Listing: Object {
    let onesAndTwos = List<OneOrTwo>()
}

But I'd like to avoid that indirection, if possible. 但我想尽可能避免这种间接访问。

List<T> property can't contain objects of different types. List<T>属性不能包含不同类型的对象。

Please learn more in docs at https://realm.io/docs/swift/latest/#relationships and https://realm.io/docs/swift/latest/#model-inheritance , that should explain why it's not possible. 请在https://realm.io/docs/swift/latest/#relationshipshttps://realm.io/docs/swift/latest/#model-inheritance中的文档中了解更多信息,这应该解释为什么它不可能。

So I suggest you to use composition over inheritance, basically the same way as you mentioned in your post. 因此,我建议您使用合成而不是继承,基本上与您在帖子中提到的方式相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM