RealmSwift: Convert Results to Swift Array

前端 未结 11 1855
[愿得一人]
[愿得一人] 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: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 = realm.objects(SomeModel.self)
    let someModelArray: [SomeModel] = someModelResults.toArray()
    

提交回复
热议问题