-1

I have a string array as strList = ["12abc", "23bcd", "12shsh", "23xyz"] Is there any way to sort the array according to just first two characters of each string?

1 Answers1

4

just try this

var strList = ["12abc", "23bcd", "12shsh", "23xyz","13das","21dadsd"]
var sortArray = strList.sorted()
debugPrint(strList)
print(sortArray)

the console result will show in below

["12abc", "23bcd", "12shsh", "23xyz", "13das", "21dadsd"]
["12abc", "12shsh", "13das", "21dadsd", "23bcd", "23xyz"]
Adarsh KC
  • 449
  • 3
  • 18
  • 1
    but if, strList = ["12shsh", "23bcd", "12abc", "23xyz","13das","21dadsd"] then the output will be 12shsh, 12abc..... So i need to sort by first 2 digit – Taohidur Imran Dec 21 '19 at 10:07
  • 3
    Note that you cannot rely on the order of same-sorted elements, since Swift's sort algorithm does not guarantee a stable sort. – Gereon Dec 21 '19 at 10:25