RealmSwift: Convert Results to Swift Array RealmSwift: Convert Results to Swift Array ios ios

RealmSwift: Convert Results to Swift Array


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}