Realm: Results als List

前端 未结 3 1070
小蘑菇
小蘑菇 2021-02-13 22:17

Is it possible to convert Results to List or shouldn\'t I do this?

In my case I have method that has List as a parameter. I w

相关标签:
3条回答
  • 2021-02-13 22:23

    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) { … }
    
    0 讨论(0)
  • 2021-02-13 22:31

    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.

    0 讨论(0)
  • 2021-02-13 22:35

    We can use extensions to make life easier :

    extension Realm {
        func list<T: Object>(_ type: T.Type) -> List<T> {
            let objects = self.objects(type)
            let list = objects.reduce(List<T>()) { list, element -> List<T> in
                list.append(element)
                return list
            }
            
            return list
        }
    }
    

    Usage:

    let objects = realm.list(YourObject.self)
    
    0 讨论(0)
提交回复
热议问题