Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift - How sort alphabetically annotations array

My project is a map with a lot of annotations points, and user could look for a specific annotation thanks to a pickerView. All is fine except the list of all annotations points seems randomly displayed. I would like to sort the annotations alphabetically.

Here s my current working code :

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        return self.mapView.annotations[row].title ?? "No title"

    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        self.mapView.selectAnnotation(self.mapView.annotations[row], animated: true)
    }

I ve tried to implement this, but without any success...

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

let sortedNames = self.mapView.annotations.sorted(by: {$0.title < $1.title})
        return sortedNames[row].title ?? "No title"

    }

I ve got this error:

Cannot convert value of type 'String??' to expected argument type 'UIContentSizeCategory'

Any hint would be greatly appreciated.

like image 901
Hugo75 Avatar asked Mar 20 '26 16:03

Hugo75


1 Answers

I'm aware this question is a bit old to answer but for anyone else having the issue the problem is that the String can not be optional. The fix it to either provide a default value or force unwrap it. For example this would be one solution to the question:

let sortedNames = self.mapView.annotations.sorted(by: { ($0.title ?? "") < ($1.title ?? "") }))
return sortedNames[row].title ?? "No title"
like image 146
Jack Hopkins Avatar answered Mar 24 '26 13:03

Jack Hopkins