-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?

8
  • 1
    Sort by prefix(2) Commented Dec 21, 2019 at 9:41
  • Have you tried strList.sorted()? Commented Dec 21, 2019 at 9:44
  • 1
    How do you expect this sort by prefix to differ from plain .sort() or .sorted() results? Commented Dec 21, 2019 at 9:48
  • need to sort by prefix(2) but how to do in code? Commented Dec 21, 2019 at 9:57
  • 1
    How to do in code? This is very easy and very basic stuff. Please read the linked documentation and the Swift Language Guide about closures. There are examples how to use sort(ed) by closure. Commented Dec 21, 2019 at 10:09

1 Answer 1

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"]
Sign up to request clarification or add additional context in comments.

2 Comments

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
Note that you cannot rely on the order of same-sorted elements, since Swift's sort algorithm does not guarantee a stable sort.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.