The project is an iOS app using Xcode 9.2 and Swift 4. Please note the Binary Search section since it's the key part of the project.
There are two view controllers, CitiesViewController and MapViewController.
To keep the view controllers more manageable, I wrote extensions for each extra protocol in the controllers. For example, the CitiesViewController includes these extensions to separate the code blocks:
extension CitiesViewController: UITableViewDataSourceextension CitiesViewController: UITableViewDelegateextension CitiesViewController: UISearchResultsUpdating
It contains a SearchController to perform the searches and a TableView to show the results. It performs a segue to the MapViewController to show the map of the selected city. It takes the data from CitiesController.
Standard ViewController with a MKMapView. It gets the city as a parameter passed from CitiesViewController.
There is one data controller, CitiesController.
It uses a shared instance since there is need for initialization.
The initial idea was to return an array of results to CitiesViewController, but due to the performance optimizations required for 200,000+ items, all the cities are stored in the items array, and the results to show are in the range stored in resultsIndex.
The default implementation of just filtering the items array was really slow, around 0.4 seconds per search. To improve the performance, I modified the code to keep all the cities in the items array and using resultsIndex to keep the indexes of the first and last elements valid for the search. There was some improvement, but it was still around 0.25 seconds per search using the Array.index method.
The Array.index method goes through the items secuentially, so it is very slow and unnecessary since the items array is sorted. So, I decided to implement a binary search that is, in this case, 3 orders of magnitude faster (around 0.0001-0.0003 seconds per search). That makes the user experience so much better because now results are shown instantly while typing.
There are two data clases: City and Coordinates:
- City is a Decodable struct that contains the necessary fields for the project. It also contains the property nameAndCountry which returns the format needed for the cell and searchValue, which is a lowercased version of nameAndCountry. It is not a getter because it is read multiple times during sorting and it slowed down the load of the app from around 6 seconds to around 25 seconds. To avoid that, the value is set by
CitiesController.parseSearchValues()after all cities are loaded from the JSON file. - Coordinates is in a struct that contains the latitude and longitude of the city. City contains a property
coordinatethat uses the lat and lon values to return a properCLLocationCoordinate2Dobject.
There are tests for the CitiesController class with searches that return valid results and searches that return no results.
There are no external dependencies to the project.
Thank you!