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?
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:
filter
removes the nil
cases, and by the time we come to sorted
, name
has to be presentIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With