Swift Sorting
🔃 Swift Sorting – Complete Beginner to Advanced Guide (With Examples & Output)
Sorting is a core operation in Swift, used for arrays, custom objects, and performance-critical code.
This guide covers basic → advanced sorting, exactly what’s asked in interviews and real projects.
1️⃣ Basic Sorting (sorted vs sort) ⭐
sorted() → returns a new array
Output
sort() → sorts in place
Output
📌 Interview tip
-
sorted()→ immutable arrays -
sort()→ mutable arrays (var)
2️⃣ Descending Order ⭐
Output
3️⃣ Sorting Strings ⭐
Output
📌 Default sorting is lexicographical (ASCII-based)
Case-Insensitive Sort ⭐⭐
4️⃣ Sorting with Custom Logic (Closures) ⭐⭐
Output
5️⃣ Sorting Custom Objects ⭐⭐⭐ (Interview Favorite)
Example Model
Sort by Marks (Ascending)
Sort by Name (Descending)
6️⃣ Multiple-Criteria Sorting ⭐⭐⭐
📌 Sort by marks first, then name
7️⃣ Sorting Dictionaries ⭐⭐⭐
Dictionaries are unordered, so you must convert them first.
Output
📌 Result type: [(key: String, value: Int)]
8️⃣ Stable Sorting (Important Concept) ⭐⭐
Swift’s sort is not guaranteed stable.
✔ Stable alternative:
📌 Preserves original order for equal keys
9️⃣ Sorting with Comparable ⭐⭐⭐
Conform to Comparable
Use Direct Sorting
🔟 Performance & Best Practices ⭐⭐⭐
| Tip | Why |
|---|---|
Prefer sort() |
No extra memory |
Use lazy when chaining |
Better performance |
| Avoid sorting repeatedly | Cache results |
Use Comparable |
Cleaner code |
1️⃣1️⃣ Common Mistakes ❌
❌ Using sorted() when mutation needed
❌ Forgetting dictionaries are unordered
❌ Complex closure hurting readability
❌ Sorting inside loops
📌 Interview Questions (Swift Sorting)
Q1. Difference between sort() and sorted()?
👉 In-place vs new array
Q2. Are Swift sorts stable?
👉 Not guaranteed
Q3. How to sort custom objects?
👉 Closures or Comparable
Q4. How to sort dictionary?
👉 Convert to array first
✅ Summary
✔ sorted() → returns new array
✔ sort() → modifies array
✔ Closures enable custom logic
✔ Custom types use Comparable
✔ Dictionaries require conversion
✔ Stable sorting needs extra logic
✔ Very important for Swift interviews
