Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

728
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!