Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RealmSwift: Convert Results to Swift Array

Tags:

ios

swift

realm

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

let array = Array(results) // la fin

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
}

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

This an another way of converting Results into Array with an extension with Swift 3 in a single line.

extension Results {
    func toArray() -> [T] {
        return self.map { $0 }
    }
}

For Swift 4 and Xcode 9.2

extension Results {
    func toArray<T>(type: T.Type) -> [T] {
        return flatMap { $0 as? T }
    }
}

With Xcode 10 flatMap is deprecated you can use compactMap for mapping.

extension Results {
    func toArray<T>(type: T.Type) -> [T] {
        return compactMap { $0 as? T }
    }
}