Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm: Results<T> als List<T>

Tags:

ios

swift

realm

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>)

like image 678
netshark1000 Avatar asked Oct 27 '15 09:10

netshark1000


3 Answers

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.

like image 70
Pulsar Avatar answered Nov 07 '22 00:11

Pulsar


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) { … }
like image 41
marius Avatar answered Nov 07 '22 01:11

marius


I would create an extension for Results with a computed variable:

extension Results {
  var list: List<Element> {
    reduce(.init()) { list, element in
      list.append(element)
      return list
    }
  }
}

Then you can use it like this:

// results is a variable of type Results<SomeElement>
let list = results.list
like image 3
Rouger Avatar answered Nov 07 '22 02:11

Rouger