Realm: Results<T> als List<T>

南楼画角 提交于 2019-11-30 01:50:42

问题


Is it possible to convert Results<T> to List<T> or shouldn't I do this?

In my case I have method that has List as a parameter. I want to call this method with fetched objects (Results<T>) and with computed objects (List<T>)


回答1:


Results and List implement CollectionType and RealmCollectionType. The latter is a specialization of the former protocol, which allows you to efficiently use aggregation functions and filter & sort entries.

Almost no method in Realm Swift make strong assumptions about the type of the collection. They just expect a SequenceType which is a generalization of the former CollectionType. For your own method, I'd recommend to go the same way. You can reach that by declaring it like shown below.

func foo<T, S: SequenceType where S.Generator.Element == T>(objects: S) { … }



回答2:


Results implements the CollectionType protocol so you could use reduce to convert it:

let results: Results<MyObject> = ...
let converted = results.reduce(List<MyObject>()) { (list, element) -> List<MyObject> in
    list.append(element)
    return list
}

You could put this code in an extension or however you like.



来源:https://stackoverflow.com/questions/33363972/realm-resultst-als-listt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!