CodexBloom - Programming Q&A Platform

Swift - Sorting an Array of Structs with Optional Properties Produces Unexpected nil Values

👀 Views: 58 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-18
swift sorting optionals array Swift

I'm collaborating on a project where I've been banging my head against this for hours. I tried several approaches but none seem to work... I tried several approaches but none seem to work. I'm facing an issue sorting an array of structs in Swift where some properties are optional. I have the following struct defined: ```swift struct Person { var name: String var age: Int? } ``` I created an array of `Person` objects with varying ages, as shown below: ```swift let people = [ Person(name: "Alice", age: 30), Person(name: "Bob", age: nil), Person(name: "Charlie", age: 25), Person(name: "Diana", age: nil) ] ``` I want to sort this array primarily by age, treating `nil` values as the highest age (i.e., they should come at the end of the sorted array). I used the following sorting method: ```swift let sortedPeople = people.sorted { (p1, p2) -> Bool in if let age1 = p1.age, let age2 = p2.age { return age1 < age2 } else if p1.age == nil && p2.age == nil { return false // or true, doesn't matter in this case } else { return p1.age != nil // This should make nil values come last } } ``` However, I receive an unexpected output where `nil` values seem to interfere with the sorting order. The result appears as: ```swift [ Person(name: "Charlie", age: 25), Person(name: "Alice", age: 30), Person(name: "Diana", age: nil), Person(name: "Bob", age: nil) ] ``` I expected the output to place `Bob` and `Diana` after `Alice` and `Charlie`, but it seems the sorting logic is incorrect because of how `nil` is evaluated. I've tried adjusting the comparison logic and even considered using a custom key for sorting, but nothing seems to work. Can anyone suggest a proper way to handle sorting with optional properties while ensuring `nil` values are placed correctly at the end? I'm working on a API that needs to handle this. What am I doing wrong? Any help would be greatly appreciated! My development environment is macOS. Thanks in advance! I recently upgraded to Swift LTS. Could someone point me to the right documentation? Any feedback is welcome!