Swift 2.1 - Results<T> as a UITableViewController dataSource - when you need an Array to sort

16 views
Skip to first unread message

Damian Esteban

unread,
Feb 21, 2016, 7:51:46 PM2/21/16
to Realm
As the title clearly states, I'm using a `UITableViewController` with Realm `Results<T>` as the data source.  Example:

...

var places: Results<Place>?

init
() {

       
super.init(nibName: "PlacesViewController", bundle: nil)
}


required init
?(coder aDecoder: NSCoder) {
   
super.init(coder: aDecoder)
}

override func viewDidLoad() {
       
super.viewDidLoad()

         
...
       places
= realm.objects(Place)
}


And this is all well and good.  However, I also need to sort my Results by distance:

func sortPlacesByDistanceFromUser(userLocation: CLLocation) -> [Place] {
        let realm
= try! Realm()

        let placesSortedByDistance
= realm.objects(Place).sort { (a, b) -> Bool in

           
return a.location!.distanceFromLocation(userLocation) < b.location!.distanceFromLocation(userLocation)
       
}
       
return venuesSortedByDistance
}



This function return an `Array`, because (as far as I know) `Results<T>` cannot be sorted like this.  Is there a way to convert an `Array` back into `Results`?  Am I missing something obvious?


Thank you.


Reply all
Reply to author
Forward
0 new messages