0

I try to sort tableviewCells by a number inside a label of each cell... for sorting I use following code:

struct sortJobs {
    let sDistance = JobTableViewCell.takenLocation
}
var sJobs = [sortJobs]()

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
        self.sJobs.sort(by: {$0.sDistance < $1.sDistance}) -> ERROR
        self.tableView.reloadData()
}

Where I take the takenLocation from:

static var takenLocation: String?

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let lastLocation = locations.last {
            let distance = myLocation.distance(from: jobLocation) / 1000
            print(String(format: "The distance to the Job is %.01fkm", distance))
            self.distance.text = String(format: "%.01fkm", distance)
            JobTableViewCell.takenLocation = self.distance.text
        }

Does someone have an idea how I can solve Binary operator '<' cannot be applied to two 'String?' operands ? Or maybe a new way to sort the cells?

J. Doe
  • 285
  • 4
  • 13
  • 1
    Unwrap as `{ ($0.sDistance ?? "") < ($1.sDistance ?? "") }` – Kamran Sep 05 '19 at 20:06
  • Changed duplicate to https://stackoverflow.com/a/44808567/3141234 , which is a better fit. – Alexander Sep 05 '19 at 20:09
  • Why is `distance` a `String?` :| – Alexander Sep 05 '19 at 20:09
  • @Kamran doesn't work - it won't get sorted by the numbers – J. Doe Sep 05 '19 at 20:16
  • @Alexander sorry, but I'm totally new to this - if it really fits, could you explain me in how far I need to change my code? – J. Doe Sep 05 '19 at 20:16
  • @Alexander I would say because I "saved" it as one before I formated it to %.01km – J. Doe Sep 05 '19 at 20:18
  • 1
    @J.Doe You've basically implemented "caching" for your string value. Caching trades of memory for time, by storing the results of previous computations for quick access in the future. In your case, you're not using much memory, nor saving much time, so your caching isn't really doing anything besides adding complexity. It's much better to only ever store core sources of truth (e.g. distance as a `Measurement`, or `CLLocationDistance`), and compute derived values (the distance formatted into a `String`) when needed (e.g. via a `formattedDistance: String` computed property) – Alexander Sep 05 '19 at 20:29
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/199034/discussion-between-alexander-and-j-doe). – Alexander Sep 05 '19 at 20:29

0 Answers0