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?
Asked
Active
Viewed 679 times
-1
-
1[Sort](https://developer.apple.com/documentation/swift/array/2296815-sorted) by `prefix(2)` – vadian Dec 21 '19 at 09:41
-
Have you tried `strList.sorted()`? – Maysam Dec 21 '19 at 09:44
-
1How do you expect this sort by prefix to differ from plain `.sort()` or `.sorted()` results? – Gereon Dec 21 '19 at 09:48
-
need to sort by prefix(2) but how to do in code? – Taohidur Imran Dec 21 '19 at 09:57
-
@Maysam yes but it sort for full string. – Taohidur Imran Dec 21 '19 at 10:03
-
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](https://docs.swift.org/swift-book/LanguageGuide/Closures.html). There are examples how to use `sort(ed)` by closure. – vadian Dec 21 '19 at 10:09
-
@vadian it is not easy, sort by first 2 characters is unavailable in swift language guide. – Taohidur Imran Dec 21 '19 at 10:13
-
It is easy. Please read also the duplicate, rather than `fileID` use `prefix(2)` – vadian Dec 21 '19 at 10:14
1 Answers
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
-
1but 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
-
3Note 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