Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array of custom objects based on optional string property in Swift

I am trying to sort an array in swift of type 'ObjCClass' which is an objective c class. 'ObjCClass' has property 'name' which is an optional of type String. I want to sort the objects in the array in ascending order based on the 'name' property. How can I do this without force unwrapping?

I've tried using this:

var sortedArray = unsortedArray.sorted(by: { $0.name as String! < $1.name as String!})

I've been trying to use the guard and if/let statements to check if the property 'name' exists but I keep running into errors since I don't think I am doing it properly. How can I check if the property exists for every object in the array and then do the sorting?

like image 380
Anubhav Saini Avatar asked Mar 27 '19 13:03

Anubhav Saini


1 Answers

First filter out the unwanted entries, then compare name with a force-unwrap

var sortedArray = unsortedArray
    .filter { $0.name != nil }
    .sorted { $0.name! < $1.name! }

NOTE:

  • Force unwrap is fine in this circumstance because filter removes the nil cases, and by the time we come to sorted, name has to be present
like image 71
staticVoidMan Avatar answered Oct 20 '22 22:10

staticVoidMan