Reputation: 249
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.
Upvotes: 3
Views: 865
Reputation: 432
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"
Upvotes: 8
Reputation: 146
I've just had exactly this error when trying to sort an array of a different class by a string property. The problem appears to be that the property you are sorting by is optional. Using a non-optional property works as expected, using an optional property gives the somewhat bizarre 'UIContentSizeCategory' error.
Something like this should do what you need:
let sorted = self.mapView.annotations { (a1, a2) -> Bool in
if let s1 = a1.title {
if let s2 = a2.title {
return s1 > s2
}
}
return false
}
Upvotes: 0