RealmSwift: Convert Results to Swift Array

With Swift 4.2 it's as simple as an extension:

extension Results {
    func toArray() -> [Element] {
      return compactMap {
        $0
      }
    }
 }

All the needed generics information is already a part of Results which we extend.

To use this:

let someModelResults: Results<SomeModel> = realm.objects(SomeModel.self)
let someModelArray: [SomeModel] = someModelResults.toArray()

If you absolutely must convert your Results to Array, keep in mind there's a performance and memory overhead, since Results is lazy. But you can do it in one line, as results.map { $0 } in swift 2.0 (or map(results) { $0 } in 1.2).


I found a solution. Created extension on Results.

extension Results {
    func toArray<T>(ofType: T.Type) -> [T] {
        var array = [T]()
        for i in 0 ..< count {
            if let result = self[i] as? T {
                array.append(result)
            }
        }

        return array
    }
}

and using like

class func getSomeObject() -> [SomeObject]? {
    let objects = Realm().objects(SomeObject).toArray(SomeObject) as [SomeObject]

    return objects.count > 0 ? objects : nil
}

Weird, the answer is very straightforward. Here is how I do it:

let array = Array(results) // la fin

Tags:

Ios

Swift

Realm