Can I have a heterogeneous collection in Realm Swift?

时间:2017-04-10 01:14:33

标签: swift realm

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.

1 个答案:

答案 0 :(得分:0)

List<T>属性不能包含不同类型的对象。

请在SciPy 2015https://realm.io/docs/swift/latest/#relationships的文档中了解详情,这可以解释为什么它不可能。

因此,我建议您使用合成而非继承,基本上与您在帖子中提到的相同。

相关问题