RealmSwift: Convert Results to Swift Array

前端 未结 11 1811
[愿得一人]
[愿得一人] 2020-12-12 15:50

What I want to implement:

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

    return objects.count > 0 ? o         


        
相关标签:
11条回答
  • 2020-12-12 16:22

    it's not a good idea to convert Results to Array, because Results is lazy. But if you need try this:

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

    but better way is to pass Results wherever you need. Also you can convert Results to List instead of Array.

    List(realm.objects(class))
    

    if the first func is not working you can try this one:

    var refrenceBook:[RefrenceProtocol] = []
    let faceTypes = Array(realm.objects(FaceType))
    refrenceBook = faceTypes.map({$0 as FaceType})
    
    0 讨论(0)
  • 2020-12-12 16:22

    I'm not sure, if there is any efficient way to do this.

    But you can do it by create a Swift array and append it in the loop.

    class func getSomeObject() -> [SomeObject]? {
        var someObjects: [SomeObject] = []
        let objects = Realm().objects(SomeObject)
        for object in objects{
            someObjects += [object]
        }
        return objects.count > 0 ? someObjects : nil
    }
    

    If you feel it's too slow. I recommend you to pass around Realm Results object directly.

    0 讨论(0)
  • 2020-12-12 16:23

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

    let array = Array(results) // la fin
    
    0 讨论(0)
  • 2020-12-12 16:26

    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
    }
    
    0 讨论(0)
  • 2020-12-12 16:32
    extension Results {
        var array: [Element]? {
            return self.count > 0 ? self.map { $0 } : nil
        }
    }
    

    So, you can use like:

    Realm().objects(SomeClass.self).filter("someKey ENDSWITH %@", "sth").array
    
    0 讨论(0)
  • 2020-12-12 16:36

    Solution for Swift 4, Realm 3

    extension Results {
        func toArray<T>(ofType: T.Type) -> [T] {
            let array = Array(self) as! [T]
            return array
        }
    }
    

    Now converting can be done as below

    let array = Realm().objects(SomeClass).toArray(ofType: SomeClass.self)
    
    0 讨论(0)
提交回复
热议问题