Swift Sorting

Swift Tutorial

🔃 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

[1, 2, 3, 4]
[4, 1, 3, 2]

sort() → sorts in place


 

Output

[1, 2, 3, 4]

📌 Interview tip

  • sorted() → immutable arrays

  • sort() → mutable arrays (var)


2️⃣ Descending Order ⭐


 

Output

[20, 15, 10, 5]

3️⃣ Sorting Strings ⭐


 

Output

["Banana", "Swift", "apple"]

📌 Default sorting is lexicographical (ASCII-based)


Case-Insensitive Sort ⭐⭐


 


4️⃣ Sorting with Custom Logic (Closures) ⭐⭐


 

Output

[11, 2, 3, 9]

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

[("A", 90), ("B", 85), ("C", 70)]

📌 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

You may also like...