5

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?

1
  • The entries with a nil name, I just want to skip them and not have them in my sorted array. Commented Mar 27, 2019 at 14:14

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.