0

I have built the following "helper" function, which takes as parameters:

  • 'unsortedArray': The array of Venue objects required to be sorted by its .venueID string property
  • 'sortingGeoArray': the Geofire string keys to be used as reference to order the unsorted array above.

and it returns a sorted array of type [Venue] via an escaping handler.

I have tried to implement this nice and simple solution suggested on the following thread:

'Sorting a Swift array by ordering from another array'

    func sortVenuesArraybyGeofireKeys(unsortedArray: [Venue], sortingGeoArray: [String] , handler: @escaping (_ sortedArray: [Venue]) -> ()){

    let ordering = Dictionary(uniqueKeysWithValues: sortingGeoArray.enumerated().map { ($1, $0) })
    let sorted: [Venue] = unsortedArray.sorted{ ordering[$0.venueID]! < ordering[$1.venueID]! }

    handler(sorted)

}

I have tried the sorting code above in multiple places through out my code by I always get a "Unexpectedly found nil while unwrapping an Optional value" at the following line (works when i test it an playground):

let sorted: [Venue] = unsortedArray.sorted{ ordering[$0.venueID]! < ordering[$1.venueID]!

On my debug window below, I have a feeling that the .map function into the let 'ordering' is not working and therefore finding nil on the next line

any help would be appreciated.

enter image description here

UPDATE: thanks to the support below, it appears that my Geofire query below in particular the 'append' to venueGeoKeys [string] array is not appending the key values, hence why found nil when I execute the function to sort.

        let query = self.GEOFIRE_VENUES.query(at: location, withRadius: 1000)
    query.observe(.keyEntered) { (key: String!, location: CLLocation!) in

        self.venueGeoKeys.append(key)
    }
Roggie
  • 1,157
  • 3
  • 16
  • 40
  • Your code will only work if every venueId found in `unsortedArray` exists in the `sortingGeoArray` array. Your code is crashing because this isn't true when you run your code. – rmaddy Apr 06 '18 at 03:03
  • thanks for pointing me in this direction. the following code is not appending the geoReference to the arrary which is then passed to the function above. I printed the count to the console and it returns 0 let query = self.GEOFIRE_VENUES.query(at: location, withRadius: 1000) query.observe(.keyEntered) { (key: String!, location: CLLocation!) in self.venueGeoKeys.append(key) } – Roggie Apr 06 '18 at 03:07
  • @rmaddy I have updated my question above. – Roggie Apr 06 '18 at 03:16
  • You need to show all of this code in context. Show when and where you call this query and when and where you call your `sortVenuesArraybyGeofireKeys` method. – rmaddy Apr 06 '18 at 03:41

0 Answers0