RealmSwift: Convert Results to Swift Array

前端 未结 11 1812
[愿得一人]
[愿得一人] 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:36
    extension Results {
        func materialize() -> [Element] {
            return Array(self)
        }
    }
    
    0 讨论(0)
  • 2020-12-12 16:38

    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 }
        }
    }
    
    0 讨论(0)
  • 2020-12-12 16:39

    Swift 3

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

    Usage

    class func getSomeObject() -> [SomeObject]? {
       let defaultRealm = try! Realm()
        let objects = defaultRealm.objects(SomeObject.self).toArray(ofType : SomeObject.self) as [SomeObject]
    
        return objects.count > 0 ? objects : nil
    }
    

    Alternative : Using generics

    class func getSomeObject() -> [T]? {
            let objects = Realm().objects(T.self as! Object.Type).toArray(ofType : T.self) as [T]
    
            return objects.count > 0 ? objects : nil
    }
    
    0 讨论(0)
  • 2020-12-12 16:41

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

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

    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()
    
    0 讨论(0)
提交回复
热议问题