Friday, May 18, 2018

Case-sensitive and Case-Insensitive sorting


There are two types of alphabetical sorting.

Case-sensitive

Capital letters are prioritised.

  • Lemon
  • Banana
  • apple


Case-insensitive

No prioritisation, pure alphabetical sorting.

  • apple
  • Banana
  • Lemon


We can achieve this compare and caseInsensitiveCompare in Array sorting.

-----------------------------------------------------------------------------------------

let arr = ["Lemon", "Mango", "apple", "banana", "Grapes"]

let sortedArr = arr.sorted { $0.compare($1) == .orderedAscending }

let sortedCaseInsensitiveArr = arr.sorted { 
           $0.caseInsensitiveCompare($1) == .orderedAscending }

sortedArr ["Grapes", "Lemon", "Mango", "apple", "banana"]


sortedCaseInsensitiveArr ["apple", "banana", "Grapes", "Lemon", "Mango"]

-----------------------------------------------------------------------------------------

Hope this post is useful. Feel free to comment incase of any queries.


No comments:

Post a Comment